Reputation: 49
I want to print from a file a specific line, for example the fourth line or the second line. This is my code and it only displays all lines and each lines number. I'm sorry if this is a simple and stupid question, but thank you in advance :D.
FileReader fr = null;
LineNumberReader lnr = null;
String str;
int i;
try{
// create new reader
fr = new FileReader("test.txt");
lnr = new LineNumberReader(fr);
// read lines till the end of the stream
while((str=lnr.readLine())!=null)
{
i=lnr.getLineNumber();
System.out.print("("+i+")");
// prints string
System.out.println(str);
}
}catch(Exception e){
// if any error occurs
e.printStackTrace();
}finally{
// closes the stream and releases system resources
if(fr!=null)
fr.close();
if(lnr!=null)
lnr.close();
}
}
}
Upvotes: 2
Views: 101
Reputation: 1751
How about this.
public static void main(String[] args)
{
int lineNo = 2; // Sample line number
System.out.println("content present in the given line no "+lineNo+" --> "+getLineContents(lineNo));
}
public static String getContents(int line_no) {
String line = null;
try(LineNumberReader lineNumberReader = new LineNumberReader(new FileReader("path\\to\\file")))
{
while ((line = lineNumberReader.readLine()) != null) {
if (lineNumberReader.getLineNumber() == line_no) {
break;
}
}
}
catch(Exception exception){
System.out.println("Exception :: "+exception.getMessage());
}
finally{
return line;
}
}
With the help of try-with-resources statement you can avoid closing stream explicitly, everything takes care by them.
Upvotes: 0
Reputation: 2031
The easiest way is to simply keep track of which line you're reading. It looks like you want to use i
for that. Don't forget to break
out of the loop once you've read the line you want.
Also, the continue statement says "skip everything else and move to the next iteration".
See The while and do-while Statements
while((str=lnr.readLine())!=null)
{
i=lnr.getLineNumber();
if(i != 57) continue;
System.out.print("("+i+")");
// prints string
System.out.println(str);
break;
}
Keep in mind that, as the comment below mentioned, LineNumberReader begins reading at 0
. So, this would actually return line 56 in natural ordering. If you want 57 in natural ordering, you can use this conditional statement instead.
if(i <= 57) continue;
Upvotes: 2
Reputation: 94
Put some counter inside loop and add aditional condition to while loop e.g counter < 4. I think it should work as you want to.
Upvotes: 0
Reputation: 1109
how about
if(i == 2){
System.out.println(str);
break;
}
instead of 2 you can give the number in as a commandline argument or user-input.
Upvotes: 1