If you want to print line number along with the lines of the file you can do that using LineNumberReader
in
Java.
LineNumberReader class has a method getLineNumber()
that gives the current line number of the file. So, wrap
your Reader object with in the LineNumberReader to get this extra functionality to get line numbers.
Printing lines of the file with line number Java code
If you have a file named abc.txt with the following content:
This is a test file. Line number reader is used to read this file. This program will read all the lines. It will give the count.
Then you can get the line numbers using the following Java code.
import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.LineNumberReader; public class LineNumberDemo { public static void main(String[] args) { LineNumberReader reader = null; try { reader = new LineNumberReader(new FileReader(new File("F:\\abc.txt"))); String str; // Read file till the end while ((str = reader.readLine()) != null){ System.out.println(reader.getLineNumber() + "- " + str); } } catch (Exception ex) { ex.printStackTrace(); } finally { if(reader != null){ try { reader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
Output
1- This is a test file. 2- Line number reader is used to read this file. 3- This program will read all the lines. 4- It will give the count.
That's all for this topic Java Program to Print Line Numbers With Lines in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Programs Page
Related Topics
You may also like-
No comments:
Post a Comment