Read file contents into an ArrayList

◇◆丶佛笑我妖孽 提交于 2019-12-02 11:12:34

问题


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. How do I step through the ArrayList adding each item separately?

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

Code:

   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;
    }

回答1:


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

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




回答2:


The if condition will always be 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);
    }

To append to an ArrayList use its add() method. ArrayList has a method size() which you could use to determine if the file contained more than ten inputs.

EDIT:

The terminating condition of your for loop should be based on numbers.length, and not ten.



来源:https://stackoverflow.com/questions/8886510/read-file-contents-into-an-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!