将文件中的每个单词放入数组列表中



Buffered Readers新手,我正在尝试将文件放入数组列表中。。。这就是我到目前为止所拥有的。

  FileReader in = new FileReader(latestFile);
    BufferedReader br = new BufferedReader(in);
    int arrayCount = 0;
    String[] array = null;
    String nextLine = null;
    if ((nextLine = br.readLine()) != null ) {
        arrayCount = array.length;
        array[arrayCount - 1] = nextLine.split("\s+");
    }

有人能解释一下我做错了什么吗?

只需将String[] array = null;更改为List<String> arrayList = new ArrayList<>();,将array[arrayCount - 1] = nextLine.split("\s+");更改为arrayList.add(nextLine.split("\s+"));

即使用ArrayList而不是未定义的数组。

BufferedReader file = new BufferedReader(new FileReader("yourfile.txt"));
ArrayList<String> array = new ArrayList<String>();
String line;
while ((line = file.readLine()) != null) 
{
    array.add(line.split("\s+"));
}
file.close();

基本上,您可以逐行读取文件,并将每一行添加到字符串数组列表中。

如果你想访问元素,你可以这样做:

for (int i=0; i < array.size(); i++)
   System.out.println(array.get(i)); 
  • 问题是您还没有初始化Array对象,要做到这一点,您必须知道要从文件中读取的元素数量。因此,您可以将阵列初始化为

    String[] array = new String[The Number];
    
  • 由于您不太可能知道数组中的元素数量,因此必须使用ArrayList

    FileReader in = new FileReader(latestFile);
    BufferedReader br = new BufferedReader(in);
    // This list will dynamically grow as elements are inserted.
    ArrayList<String> arraylist = new ArrayList<String>();
    String nextLine = null;
    if ((nextLine = br.readLine()) != null ) {
      arraylist.addAll(Arrays.asList(line.split("\s+")));
    }
    // if you want an array, following code will return all the 
    //elements as String array
    String[] array = arraylist.toArray(new String[0]);
    

    使用ArrayList会很容易。

    希望这能有所帮助。