Java Read a File Line by Line

In this Java tutorial, we will learn to read a text file line-by-line methods such as Streams or FileReader. We will also learn to iterate through lines and filter the file content based on some conditions.

1. Files.lines() – Stream through Lines of a File in Java 8

The Files.lines() is a new addition in Java 8. It reads all lines from a file as a Stream. The returned stream contains a reference to an open file. The file is closed by closing the stream.

It is important to note that the file contents should not be modified during the execution of the terminal stream operation, or else the result of the terminal stream operation is undefined.

As a recommended practice, Files.lines() must be used within a try-with-resources statement or similar control structure to ensure that the stream’s open file is closed promptly after the stream’s operations have been completed.

Path filePath = Paths.get("c:/temp", "data.txt");
 
try (Stream<String> lines = Files.lines( filePath )) {
  lines.forEach(System.out::println);
} 
catch (IOException e) {
  //...
}

2. Reading and Filtering the Lines

In this example, we will read the file content as a stream of lines. Then we will filter all lines which have the word “password” in them.

For filtering, we are passing a lambda expression, that is an instance of a Predicate, to the filter() method.

Path filePath = Paths.get("c:/temp", "data.txt");
 
try (Stream<String> lines = Files.lines(filePath)) {
 
   List<String> filteredLines = lines
          .filter(s -> s.contains("password"))
          .collect(Collectors.toList());
    
   filteredLines.forEach(System.out::println);
} 
catch (IOException e) {
  e.printStackTrace();
}

3. Reading All Lines from a Small File

If the file size is small, we can use the Files.readAllLines() method that reads all lines from a file into a List. By default, bytes from the file are decoded into characters using the UTF-8 charset.

Note that Files.readAllLines does not require explicit resource closing after we have read the file.

Path filePath = Paths.get("c:/temp", "data.txt");

List<String> lines = Files.readAllLines(filePath);

for (String line : lines) {
  System.out.println(line);
}

4. Reading a File Line by Line using FileReader [Legacy]

Till Java 7, we could read a file using FileReader in various ways. This has been mentioned for reference only, and shall not be used in Java 8 or later, as it provides no additional benefit for this usecase.

File file = new File("c:/temp/data.txt");

try (FileReader fr = new FileReader(file);
  BufferedReader br = new BufferedReader(fr);) {
  String line;
  while ((line = br.readLine()) != null) {
    System.out.println(line);
  }
} catch (IOException e) {
  e.printStackTrace();
}

5. Guava Files.readLines()

One of the simplest solutions is to use the Google Guava’s Files class its method readLines().

try {
  List<String> lines = com.google.common.io.Files.readLines(file,
    Charset.defaultCharset());
} catch (IOException e) {
  e.printStackTrace();
}

If we want to process the lines as they are read, we can use a LineProcessor. For example, in the below code, we are capitalizing the lines as they are read.

// With LineProcessor
LineProcessor<List<String>> lineProcessor = new LineProcessor<>() {
  final List<String> result = new ArrayList<>();

  @Override
  public boolean processLine(final String line) throws IOException {
    result.add(StringUtils.capitalize(line));
    return true; // keep reading
  }

  @Override
  public List<String> getResult() {
    return result;
  }
};

try {
  List<String> lines = com.google.common.io.Files
    .asCharSource(file, Charset.defaultCharset())
    .readLines(lineProcessor);
} catch (IOException e) {
  e.printStackTrace();
}

6. Commons IO’s FileUtils.readLines()

Similar to Guava, Apache Commons IO library has FileUtils class that provides a single statement solution for reading the file content in lines. The file is always closed at the end of the operation.

try {
  List<String> lines = FileUtils.readLines(file, Charset.defaultCharset());
} catch (IOException e) {
  e.printStackTrace();
}

That’s all for Java example to read a file line by line. Please put your questions in the comments section.

Happy Learning !!

Source Code on Github

Comments

Subscribe
Notify of
guest
6 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode