Search code examples
javacsvintellij-ideabufferedreader

Is there a way to read one line and the next one, iterating over a .txt file in Java?


I would like to read one line of a .txt file using BufferReader. But my question is that I need to read one line and the next one together, and then go to the next line and do it again with its next one. Here is an exemple :

A
B
C
D

I need to read A and B (and process), then B and C (process), then C and D.

Do I need to create an array to store each pair and then process? Or can I process when iterating over the file? I'm currently doing this :

while (file = in.readLine() != null) {
            String[] data = file.split(",");
            String source = data[0];
            file = in.readLine();
            String destination = data[0];        
        }

Here the goal is to put the previous destination as the next source. But then when my while loop goes on the next line, don't I skip one letter?

Thanks for your attention !


Solution

  • You could try something like this:

            String a = in.readLine();
            if (a == null) {
                return;
            }
           
            for (String b; (b = in.readLine()) != null; a = b) {
                // do smth
                
            }
    

    Maybe the reduce operation of the Stream pipeline is also helpful for you. For example, if you want to concatinate all lines together:

       Optional<String> reduce = in.lines().reduce("", (a,b) -> a+b);
       if (reduce.isPresent()) {
         // ..
       } else {
         // ...
       }