将文件内容读入 ArrayList [英] Read file contents into an ArrayList

查看:25
本文介绍了将文件内容读入 ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

On a previous project I was required to read file contents into an array. Now I have to do the same thing only I have to read the contents into an ArrayList. A few problems I am encountering is

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

  1. How do I step through the ArrayList adding each item separately?

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

If the file contains more than 10 inputs, it has to exit. I have tried the following, which does not work properly.

代码:

   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)

Instead of assigning the line to array[i], simply do arrayList.add(line)

如果这不是作业,请考虑使用一些 3rd 方实用程序,例如 apache-commons FileUtils.readLines(..) 或 guava Files.readLines(..)

If this is not homework, consider using some 3rd party utilities like apache-commons FileUtils.readLines(..) or guava Files.readLines(..)

这篇关于将文件内容读入 ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆