Reading a File Line by Line in Java

In this Java tutorial, we will learn to read a file line by line using various methods. We will also learn to iterate through lines and filter the file content based on some conditions.

1. Reading with Stream of Lines

In this example, we will read the file contents one line at a time using Java Stream API and fetch each line one at a time and check it for word "password".

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

We can also 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.

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

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

2. Reading and Filtering the Content

In this example, we will read the file content as a stream of lines as. 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();
}

We are reading the content of the given file and checking if any line contains word "password" then print it.

3. Reading a File Line by Line using FileReader

Till Java 7, we could read a file using FileReader in various ways.

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();
}

4. 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();
}

5. 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

Leave a Reply

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.