Using the LineNumberReader class
LineNumberReader is a subclass of the BufferedReader class and allows you to keep track of which line you're currently processing. It also enables you to alter the current line number if you wish to start from another number. This example constructs a LineNumberReader object for a file and reads each line until the end of file is reached. Each line is printed out along with the line number. This is what the input file (myFile.txt) looks like: This is the first line This is the second line This is the third line |
import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.LineNumberReader; /** * * @author javadb.com */ public class Main { /** * Example method for using the LineNumberReader class */ public void readFromFile(String filename) { LineNumberReader lineNumberReader = null; try { //Construct the LineNumberReader object lineNumberReader = new LineNumberReader(new FileReader(filename)); String line = null; while ((line = lineNumberReader.readLine()) != null) { System.out.println("Line " + lineNumberReader.getLineNumber() + ": " + line); } } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { //Close the BufferedWriter try { if (lineNumberReader != null) { lineNumberReader.close(); } } catch (IOException ex) { ex.printStackTrace(); } } } /** * @param args the command line arguments */ public static void main(String[] args) { new Main().readFromFile("myFile.txt"); } } |
And this is what the output will be when we run the code: Line 1: This is the first line Line 2: This is the second line Line 3: This is the third line |
Search for code examples on this site
