java-将文件内容读入ArrayList

在上一个项目中,我需要将文件内容读入数组.现在,我只需要将内容读入ArrayList中就可以做同样的事情.我遇到的一些问题是

>如何逐步遍历ArrayList分别添加每个项目?
>如果文件包含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; 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);
            }

            matrix[i] = Integer.parseInt(numbers[i]);
        }
        lineCount++;

        result += matrix;
    }

解决方法:

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

如果这不是家庭作业,请考虑使用一些第三方工具,例如apache-commons FileUtils.readLines(..)或guava Files.readLines(..)

上一篇:python-计算文件中前两个“字符串”出现之间的跳转(无行数)


下一篇:python-Errno13,尝试读取文件时权限被拒绝