如何将从 java 中的 FileReader 读取的数据内容记录到数组列表中?

How do I log the contents of the data read from a FileReader in java into an Array List?

澄清一下:下面的代码将文件 reader 中的数据记录到一个数组中。在这种情况下,我必须知道行数(例如 11)。我想使用数组列表而不是数组,这样我就不会被迫预定义索引的数量。

import java.io.*;

public class ReadMyFile {
  public static void main(String[] args) throws FileNotFoundException, IOException {
    FileReader reader = new FileReader("data.txt");
    System.out.println("We have made a FileReader");

    char [] data = new char[11];
    reader.read(data);
    for (int i = 0; i < data.length; i++) {
      System.out.print(data[i]);
    }
    reader.close();
  }
}

您可以使用 read() 方法代替 read(some_array) 方法:

List<Character> charList = new ArrayList<>()
char c;
while ((c = reader.read()) != -1) {
    charList.add(c);
}

read() 读取一个字符,因此您可以创建一个循环并一个一个地读取字符,在读取每个字符后,您可以将该字符添加到列表中。当没有更多字符可读取时 read() returns -1 并终止循环。