-2

Is there exists some another way to parse .txt file in Java except

BufferedReader reader = new BufferedReader(...);
String line;

while ((line = reader.readLine()) != null) {...}

?

I need to parse this file moving by 2 rows. Is there any way to rebuild while loop into forEach with iterator?

Thanks for the answer.

  • If it's a small enough file, then you could read the whole file into a String array/list first, then once complete you can process or iterate the array however you want. See here for an example: [Java: Reading a file into an array](https://stackoverflow.com/questions/285712/java-reading-a-file-into-an-array) – sorifiend May 09 '22 at 03:48
  • 1
    Why? What's wrong with the way you have it? How will using an iterator help? – user207421 May 09 '22 at 03:51
  • You could stick with the while loop and use a simple `if` check with a boolean flag to track when you are on the first or second line and process accordingly. – sorifiend May 09 '22 at 03:53
  • 1
    You don't need an iterator here. There is nothing wrong with `String line1, line2; while ((line1 = readLine()) != null && (line2 = reader.readLine()) != null) {...}` – user207421 May 09 '22 at 03:59
  • 1
    [`Files.readAllLines(Path)`](https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/nio/file/Files.html#readAllLines(java.nio.file.Path)) – MadProgrammer May 09 '22 at 04:02

1 Answers1

2

Is there exists some another way to parse .txt file in Java except ...

Yea. Lots of ways. For example, this small change to your example will cause it to parse two lines at a time.

BufferedReader reader = new BufferedReader(...);
String line, line2;

while ((line = reader.readLine()) != null) {
    line2 = reader.readLine();
    // Parse lines 1 and 2
}

Or you could do field by field parsing using a Scanner.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216