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 BufferedReader, Scanner, StreamTokenizer, DataInputStream, SequenceInputStream, 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.
How to create a File in Java using JDK 6, JDK 7 with NIO or Commons IO.
The many ways to write data to File using Java.
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.
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