Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

using BufferedReader in Java

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

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

1 Reply

0 votes
by (71.8m points)

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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...