How to read Files in Java

How to read Files in Java


1. Overview

In this tutorial, we'll explore different ways to read from a File in Java.

First, we'll learn how to load a file from the classpath, a URL, or from a JAR file using standard Java classes.

Second, we'll see how to read the content with BufferedReaderScannerStreamTokenizerDataInputStreamSequenceInputStream, and FileChannel. We will also discuss how to read a UTF-8 encoded file.

Finally, we’ll explore the new techniques to load and read a file in Java 7 and Java 8.

This article is part of the “Java – Back to Basic” series on Baeldung.

Further reading:

Java – Create a File

How to create a File in Java using JDK 6, JDK 7 with NIO or Commons IO.

Read more →

Java – Write to File

The many ways to write data to File using Java.

Read more →

2. Setup

2.1 Input File

In most examples throughout this article, we'll read a text file with filename fileTest.txt that contains one line:

Hello, world!

For a few examples, we'll use a different file; in these cases, we'll mention the file and its contents explicitly.

2.2 Helper Method

We'll use a set of test examples with core Java classes only, and in the tests, we'll use assertions with Hamcrest matchers.

Tests will share a common readFromInputStream method that transforms an InputStream to String for easier asserting of results:

private String readFromInputStream(InputStream inputStream)
  throws IOException {
    StringBuilder resultStringBuilder = new StringBuilder();
    try (BufferedReader br
      = new BufferedReader(new InputStreamReader(inputStream))) {
        String line;
        while