Home > Software engineering >  Write from file to ArrayList
Write from file to ArrayList

Time:04-08

For the program to work, it is necessary to write data from the file to the arraylist, but how to make the written element not equal to null in the loop? That is, so that the loop stops its execution as soon as it reads all the lines from the file

public static void readFromFile(String path, String filename) throws IOException {
    ArrayList<String> ip = new ArrayList<>();
    try {
        File file = new File(path   "\\"   filename);
        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);
        ip.add(br.readLine());
        while ((ip.add(br.readLine()) != null)) {
            //writing to a variable
        }
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }
}

CodePudding user response:

ip.add(...) returns a boolean. This code won't compile, because a boolean is a primitive, and thus can never be null.

Move the add inside the loop:

String line;
while ((line = br.readLine()) != null) {
  ip.add(line);
}

CodePudding user response:

Here is the better way to read all lines:

Files.readAllLines(Paths.get("path_to_file"), StandardCharsets.UTF_8)
  •  Tags:  
  • java
  • Related