How to write Java code to get the number of lines in a file?

You can use the LineNumberReader class to retrieve the number of lines in a file.

import java.io.FileReader;
import java.io.LineNumberReader;

public class LineCount {
    public static void main(String[] args) {
        String fileName = "path/to/file.txt";
        int lineCount = countLines(fileName);
        System.out.println("Total number of lines: " + lineCount);
    }

    public static int countLines(String fileName) {
        try (LineNumberReader reader = new LineNumberReader(new FileReader(fileName))) {
            while (reader.skip(Long.MAX_VALUE) > 0) {
                // Skip to the end of the file
            }
            return reader.getLineNumber() + 1;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }
}

The above code defines a method called countLines, which takes a file name as a parameter and returns the number of lines in the file. In the countLines method, we use LineNumberReader to read the file and skip to the end of the file using the skip method. Then, we can get the current line number by calling the getLineNumber method, and adding 1 gives us the number of lines in the file. If any exceptions occur while reading the file, we will print the exception information and return -1.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds