Tuesday, June 20, 2023

Java Program to Print Line Numbers With Lines in Java

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

  1. How to Read File From The Last Line in Java
  2. Reading Delimited File in Java Using Scanner
  3. Reading File in Java Using Files.lines And Files.newBufferedReader
  4. Writing a File Asynchronously Java Program
  5. How to Count Lines in a File in Java

You may also like-

  1. How to Create Password Protected Zip File in Java
  2. How to Read Input From Console in Java
  3. Convert int to String in Java
  4. How to Find Last Modified Date of a File in Java
  5. JavaScript Array slice() method With Examples
  6. Run Python Application in Docker Container
  7. Spring MVC Java Configuration Example
  8. Custom Async Validator in Angular Template-Driven Form

No comments:

Post a Comment