0

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());
    }
}
2
  • What's wrong with the existing code? Commented Apr 7, 2022 at 16:31
  • You should use try-with-resources to ensure that the FileReader is closed after reading from it. Commented Apr 7, 2022 at 16:37

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Here is the better way to read all lines:

Files.readAllLines(Paths.get("path_to_file"), StandardCharsets.UTF_8)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.