How can line numbers be displayed in Java?

In Java, you can use the LineNumberReader class to display line numbers. Here is an example code:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;

public class Main {
    public static void main(String[] args) {
        try {
            LineNumberReader reader = new LineNumberReader(new FileReader("example.txt"));
            String line = reader.readLine();
            while (line != null) {
                System.out.println(reader.getLineNumber() + ": " + line);
                line = reader.readLine();
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In the example above, we used the LineNumberReader class to read the file “example.txt” and display the line number before each line.

bannerAds