2015-04-05 81 views
0

如何将文件读入String []数组然后将其转换为ArrayList?将文本文件读入String数组,然后转换为ArrayList

我无法马上使用ArrayList,因为我的列表类型不适用于参数(字符串)。

所以我的教授告诉我把它放入一个String数组中,然后将其转换。

我很难过,因为我对Java仍然很陌生,所以无法理解我的生活。

+0

好像http://stackoverflow.com/questions/19844649/java-read-file-and-store-text-in-an-array的副本。一般来说,对于一个数组转换成一个列表,你可以使用'Arrays.asList(myarray的);' – 2015-04-05 23:53:09

+0

我不断收到错误“无法转换列表列出 ...... ArrayList中持有Person对象FYI – 2015-04-06 00:12:23

+0

它如果你分享了相关的代码,将会有所帮助,但总之,如果不明确地填充每个'Person',你就不能从文件中读入'Person'列表,最简单的方法是先读取“raw”字符串行,之后再进行line - >'Person'的转换。 – 2015-04-06 00:15:44

回答

0
import java.io.BufferedReader; 
import java.io.FileReader; 
import java.io.IOException; 
import java.util.ArrayList; 
import java.util.List; 

/** 
* Created by tsenyurt on 06/04/15. 
*/ 
public class ReadFile 
{ 
    public static void main(String[] args) { 

     List<String> strings = new ArrayList<>(); 
     BufferedReader br = null; 

     try { 

      String sCurrentLine; 

      br = new BufferedReader(new FileReader("/Users/tsenyurt/Development/Projects/java/test/pom.xml")); 

      while ((sCurrentLine = br.readLine()) != null) { 
       System.out.println(sCurrentLine); 
       strings.add(sCurrentLine); 
      } 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       if (br != null)br.close(); 
      } catch (IOException ex) { 
       ex.printStackTrace(); 
      } 
     } 

    } 
} 

有读取一个文件并创建一个ArrayList的一个代码,它

http://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/

0

那么有很多方法可以做到这一点, 如果你想有一个你可以使用此代码每个单词的列表中文件存在

public static void main(String[] args) { 
    BufferedReader br = null; 
    StringBuffer sb = new StringBuffer(); 
    List<String> list = new ArrayList<>(); 
    try { 

     String sCurrentLine; 

     br = new BufferedReader(new FileReader(
       "Your file path")); 

     while ((sCurrentLine = br.readLine()) != null) { 
      sb.append(sCurrentLine); 
     } 
     String[] words = sb.toString().split("\\s"); 
     list = Arrays.asList(words); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     try { 
      if (br != null) 
       br.close(); 
     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 
    } 
    for (String string : list) { 
     System.out.println(string); 

    } 
} 
相关问题