Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How can I use BufferedReader for reading all lines between two concrete line. for example i want to start reading from line1 то 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 write something like this, but it does not working! Please help me, I am beginner in Java!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
242 views
Welcome To Ask or Share your Answers For Others

1 Answer

Change the loop in following way. You need to read the line in condition and check if it's not nutll i.e. end of 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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...