Java
File Handling
Line Count
Programming Tips
Java IO

Number of lines in a file in Java

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Counting the number of lines in a file is a common task in many Java applications, whether for processing logs, data analysis, or reading configuration files. Java provides several ways to accomplish this task, each with their own advantages. This article will explore various methods to count the number of lines in a file in Java, including both traditional techniques and more modern approaches introduced in recent Java versions.

Approaches for Counting Lines in a File

1. Using BufferedReader

One of the most traditional ways to read lines from a file in Java is by utilizing BufferedReader. This class provides an efficient means of reading text from an input stream, performing buffering of characters for efficient reading.

Example:

java
1import java.io.BufferedReader;
2import java.io.FileReader;
3import java.io.IOException;
4
5public class LineCounter {
6    public static void main(String[] args) {
7        String filePath = "example.txt";
8        int lineCount = countLinesUsingBufferedReader(filePath);
9        System.out.println("Number of lines: " + lineCount);
10    }
11
12    public static int countLinesUsingBufferedReader(String file) {
13        int lines = 0;
14        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
15            while (reader.readLine() != null) {
16                lines++;
17            }
18        } catch (IOException e) {
19            e.printStackTrace();
20        }
21        return lines;
22    }
23}

2. Using Files.lines (Java 8+)

Java 8 introduced the Files class, which provides a more concise and modern way to count lines using streams. Files.lines(Path) returns a Stream<String> that represents lines of text from the file.

Example:

java
1import java.io.IOException;
2import java.nio.file.Files;
3import java.nio.file.Path;
4
5public class LineCounter {
6    public static void main(String[] args) {
7        String filePath = "example.txt";
8        int lineCount = countLinesUsingFilesLines(filePath);
9        System.out.println("Number of lines: " + lineCount);
10    }
11
12    public static int countLinesUsingFilesLines(String file) {
13        int lines = 0;
14        try {
15            lines = (int) Files.lines(Path.of(file)).count();
16        } catch (IOException e) {
17            e.printStackTrace();
18        }
19        return lines;
20    }
21}

3. Using LineNumberReader

LineNumberReader is a subclass of BufferedReader that maintains a current line number, which can be used for counting lines directly. It can be useful when you also need to track line numbers during reading.

Example:

java
1import java.io.FileReader;
2import java.io.IOException;
3import java.io.LineNumberReader;
4
5public class LineCounter {
6    public static void main(String[] args) {
7        String filePath = "example.txt";
8        int lineCount = countLinesUsingLineNumberReader(filePath);
9        System.out.println("Number of lines: " + lineCount);
10    }
11
12    public static int countLinesUsingLineNumberReader(String file) {
13        int lines = 0;
14        try (LineNumberReader reader = new LineNumberReader(new FileReader(file))) {
15            while (reader.readLine() != null) {
16                // Do nothing
17            }
18            lines = reader.getLineNumber();
19        } catch (IOException e) {
20            e.printStackTrace();
21        }
22        return lines;
23    }
24}

Comparing Different Methods

MethodJava Version RequiredStream-basedProvides Line Numbers
BufferedReaderAnyNoNo
Files.linesJava 8+YesNo
LineNumberReaderAnyNoYes

Performance Considerations

  • BufferedReader: Generally performs well due to buffering but is slightly more verbose.
  • Files.lines: Utilizes Java Streams, offering a more readable and concise syntax. It also allows easy parallel processing.
  • LineNumberReader: Suitable when you need to process lines along with their line numbers, albeit with slightly higher overhead due to maintaining state.

Additional Topics

Handling Large Files

For extremely large files, ensure that your method can handle potential OutOfMemoryError. Files.lines opens a stream that should be properly closed in a try-with-resources statement to manage resources efficiently. For additional scalability, consider processing files in chunks and leveraging parallel stream processing.

Exception Handling

When performing file I/O operations, it's essential to handle exceptions properly. All the methods outlined handle IOException, ensuring that resources are consistently closed and potential issues during file operations are managed.

Use Cases Beyond Line Counting

These techniques not only count lines but can be easily adapted for other file processing tasks such as reading specific lines, searching for patterns, or processing data line-by-line, making them versatile tools in your Java programming toolkit.

Conclusion

Counting the number of lines in a file in Java can be achieved through several methods, each with its own merits. Whether you use the traditional BufferedReader or the modern Files API, understanding these methods enhances your ability to handle file processing tasks efficiently in Java applications. By choosing the right approach, you balance readability, performance, and functionality, leading to robust and maintainable code.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.