将文件内容读入ArrayList

在之前的项目中,我需要将文件内容读入数组。 现在我必须做同样的事情,我必须将内容读入ArrayList。 我遇到的一些问题是

  1. 如何单独添加每个项目的ArrayList?

  2. 如果文件包含10个以上的输入,则必须退出。 我尝试了以下,但无法正常工作。

码:

public static String readFile(String fileName) throws IOException { String result = ""; String line = ""; FileInputStream inputStream = new FileInputStream(fileName); Scanner scanner = new Scanner(inputStream); DataInputStream in = new DataInputStream(inputStream); BufferedReader bf = new BufferedReader(new InputStreamReader(in)); int lineCount = 0; String[] numbers; while ((line = bf.readLine()) != null) { numbers = line.split(" "); for (int i = 0; i  10) { System.out.println("The file you are accessing contains more than 10 input values. Please edit the file you wish to use so that it contains" + "> 10 input values. The program will now exit."); System.exit(0); } matrix[i] = Integer.parseInt(numbers[i]); } lineCount++; result += matrix; } 

而不是将行分配给array[i] ,只需执行arrayList.add(line)

如果这不是功课,请考虑使用一些第三方实用程序,如apache-commons Files.readLines(..)或guava Files.readLines(..)

if条件始终为false

 for (int i = 0; i < 10; i++) { if(i > 10) { System.out.println("The file you are accessing contains more than 10 input values. Please edit the file you wish to use so that it contains" + "> 10 input values. The program will now exit."); System.exit(0); } 

要附加到ArrayList使用其add()方法。 ArrayList有一个方法size() ,您可以使用它来确定该文件是否包含十个以上的输入。

编辑:

for循环的终止条件应该基于numbers.length ,而不是十。