Using BufferedReader in Java

How can I use BufferedReader to read all the lines between two specific lines. For example, I want to start reading from line1 then line2, can I use this code

BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
String line1 = "StartLine";
String line2 = "EndLine";
while (!line1.equals(line2))
{
  // do something
  line1 = reader.readLine();

}       

I am writing something like this, but it does not work! Please help me, I'm starting in Java!

-2
source share
3 answers

Modify the loop as follows. You need to read the line in state and check if it is too much, for example, the end of the file.

String line1 = "StartLine";
String line2 = "EndLine";
String line3 = null;

 //Iterate upto line1
while( (line3 = reader.readLine()) != null && ! line3.equals(line1));

//Print the lines till line2
while(line3 != null && ! line3.equals(line2) ) {
     System.out.println(line3);
     line3 = reader.readLine();
}
+2
source

First you need another loop to read all the lines before your "StartLine"
and then you will need to clarify that it does NOT work.
What do you expect and what is not happening.

0

You can try using the BufferReader methods markand reset:

    BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
    String line1 = "StartLine";
    String line2 = "EndLine";
    String line;
    while ((line = reader.readLine()) != null) {
        if (line1.equals(line)) {
            System.out.println(line);
            reader.mark(100);
        }
    }
    reader.reset();
    while ((line = reader.readLine()) != null) {
        if (line2.equals(line)) {
            break;
        } else {
            System.out.println(line); //or whatever you want to do
        }
    }

}

You may have to play with value mark, but something like this might work for you.

Hope this helps.

0
source

All Articles