How to Read a File in Java

Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

Learn via video course

Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
By Tarun Luthra
Free
star5
Enrolled: 1000
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
Tarun Luthra
Free
5
icon_usercirclecheck-01Enrolled: 1000
Start Learning

Abstract

We use Files to store data in our computers. It is very important for us to able to read these files. Java provides us Functions with the help of which we can read Files. Two most common functions are Scanner and BufferedReader.

Scope

  • This article covers the File Reading operations in Java Programming, defines some basic terms like Stream and explains basic packages for reading a file.

  • We will learn to read a file using these 6 methods - Files.lines(), Files.readString(), Files.readAllBytes(), Files.readAllLines(), BufferedReader and Scanner.

Introduction

A file is a storage unit in the computer. All the non-volatile (permanent) data is saved in files. This includes app data, photos, videos, documents, and everything that is stored on our hard disks. Therefore it is very important for us to know how to read these files.

What is Stream?

As we know that conventionally, a Stream is a continuous flow of water, but in Java (and in general programming) Stream is referred to as a continuous flow of data. Therefore, a stream is a sequence of data, in the form of objects. A point to remember is that Stream is not a Data Structure, and it does not store any elements. It is just transporting the data from the source to the destination.

what is stream in java

How to Read a File in Java?

For reading a file in Java and for doing file operations, we need to import some pre defined classes. We will require these classes:

  • java.io.File
  • java.io.FileNotFoundException

We will include these packages, and other necessary input-output packages in a single line using java.io.*.

Throughout the article, we will be using readThisFile.txt, which is in the directory: C:\Bhavya\Scaler\readThisFile.txt. As we know that '\' is a special character in Java, so we will have to use it with another '\'.

So the directory is "C:\\Bhavya\\Scaler\\readThisFile.txt".

Contents of this file are :

Different Ways to Read a File Are

Method 1: Reading a file using the Files.lines() function

Files class was introduced in Java 8. It converts the whole file to a Stream of strings.

Files.lines() help us to read the data of the given file, line by line. Files.lines() closes the opened resources automatically (ie, the file), so we do not need to close the file, and we can skip try and catch blocks for Files.lines().

For using Files.lines(), we will need to define the path of the file. We can use the Paths.get() function Path library. For using this function, we need to include the java.nio.file. package*.

For using the Stream functions, we need to include java.util.stream.* package.

Syntax:

Files.Lines(PATH);

Return Type:

Stream<String>

Code:

Output:

Here we are just printing the contents of the file, but quite often we find ourselves in situations where we need to store and process the data of the file. For storing the data, we can use a list and functions of Lines.

Code:

Output:

Remember:

This is useful for small files. If we try to use a large file with this method, it can throw exceptions like java.lang.OutOfMemoryError. We can further optimize it by using the parallel function.

Method 2: Reading a file using the Files.readString() function

readString was introduced in Java 11. It helps us to save all the data of the file into a single string. Internally, Files.readString() uses Files.readAllBytes() function (it will be discussed later in this article).

Syntax:

Files.readString(PATH);

Return Type:

String

Code:

Output:

This method also allows us to read small files. If the size of the file is very large, it may throw java.lang.OutOfMemoryError exception.

Method 3: Reading a file using the Files.readAllBytes() function

The Files.readAllBytes() function was introduced in Java 7. It reads the given file and stores the data in a byte array. (A byte array is a collection of byte data type. It stores the data in the form of bits, since a byte is equal to 8 bits). We can then convert the byte array as we want. As we can see that the data is first stored in a byte array, it is not helpful to use the Files.readAllBytes() function for large files. The Files.readAllBytes() function can throw java.lang.OutOfMemoryError exception if the data is very large.

Syntax:

Files.readAllBytes(PATH);

Return Type:

byte[] ` (Byte Array).

Code:

Output:

Here is an example of converting the data from a bytes array to a binary string.

Code:

Output:

Explanation:

The ASCII code of every character is getting stored in the array, and that is the ouput.

(ASCII Code for a space is 32, and for a new line is 10).

Method 4: Reading a file using the Files.readAllLines() function

The Files.readAllLines was introduced in Java 8. It reads the given file and returns a List of String. As we can see that the data is first stored in a list of strings, it is not helpful to use the Files.readAllLines() function for large files. The Files.readAllLines() function can throw java.lang.OutOfMemoryError exception if the data is very large.

Syntax:

Files.readAllLines(PATH);

Return Type:

List<String>

Code:

Output:

Method 5: Reading a file using the BufferedReader class

The BufferedReader class was there in Java from the start and is the fastest method to read the data, from a given file, Line by Line. It is used to read the data using the input stream. As the name suggests, the BufferedReader class buffers the data in the form of small packets of size 8 KB. Since it is only processing the data of 8 KB at a particular time, it is very efficient and can be used for large files.

Syntax:

BufferedReader br = new BufferedReader(new FileReader(PATH));

Explanation:

We are creating a BufferedReader object, and then we can use the methods of BufferedReader class on it.

Code:

Since readLine() returns null as we reach the end, we can use it as the stopping condition.

Output:

Remember:

We need to close the file after the reading is done.

Method 6: Reading a file using the Scanner class

After discussing the BufferedReader method, and saying it the fastest why do we need Scanner?

The Scanner class has more useful methods like next(), nextInt(), nextByte(), nextLine() and etc, and we can assign any delimiter to divide the string rather than the default space. Since the Scanner class also reads the data from the stream Line by Line, we can use large text files to read.

Syntax:

Scanner sc = new Scanner(new File(PATH));

Explanation:

We are creating a Scanner object, and then we can use the methods of Scanner class on it.

Code:

Output:

Remember:

We need to close the file after the reading is done.

We can also print the whole file without any loops. For printing the entire file at once, without any loops, we will have to use "\\Z" as the delimiter. This delimiter is defined in Java as the end of the input.

Code:

Output:

Summary

  • A Stream is a continuous Flow of Data and not a Data Structure.
  • For reading large files, we can use BufferedReader or Scanner.
  • For splitting the file with multiple delimiters, we can use Scanner.
  • For small files (generally less than 2 GB), we can use any of the above mentioned functions.