×

Java Read File

Java provides its users with many ways of reading a file. To read a text file, you can use a FileReader, BufferedReader, or Scanner. Each utility offers something special for example, the BufferedReader provides data buffering for fast reads, and the Scanner provides analysis capabilities. The type of content in a file determines which file reader to use. Some methods are suited for faster implementation, and others are good at reading small file data. Some provide line-by-line read, while one of them reads file character by character. In the following article, we'll look at all of Java's ways to read files.

1. BufferedReader Class

To read text from a character-input stream, the class BufferedReader is utilized. It buffers characters to read input efficiently, including characters, arrays, or lines.

The buffer size is either determined by the user or by the default size, which can be used because it is large enough to handle most cases. It inherits the reader class using inheritance concepts. BufferedReader has two types of constructors, which are as follows:

  • BufferedReader( Reader in): This will utilize BufferedReader's default size.
  • BufferedReader (Reader in, int n): This will use the size specified by the user.
Java Read File

The above snippet of code is an example of how one can use BufferedReader to read contents from a file and print it.

In the first line, we have specified the path of the file. The file contains some text. We check whether the file is empty or not and then print the file's content. We can see files getting printed in the console as we run the program.

Java Read File
  • FileReader: It may seem that FileReader shares similarities with BufferedReader but has many differences. Unlike  BufferedReader,  it isn't buffered in any way. It reads data from a file and extracts characters.
    It is, on the whole, slower and less efficient than BufferedReader.
    FileReader has the following Constructors.
  • FileReader ( File file): It gets the file's name in the file instance.
  • FileReader(String fileName): First, it opens the file. If the file is not present in the specified path, then it will throw FileNotFoundException
Java Read File Java Read File

Unlike the BufferedReader, the text is printed word by word as FileReader extracts characters from a text file.

  • Scanner class: The Scanner class can also be used to read text from a text file. Following are the constructors provided by the Scanner class in JavaJava.
  • Scanner (File Source): This function reads data from a File object that represents a file.
  • Scanner (InputStream source): To read data from an InputStream, call this method.
  • Scanner (Path source): This method reads the file that the object specifies.
Java Read File Java Read File

Following is an implementation of the Scanner class.

There's another way to read the entire file. Instead of using a while loop, we can use the following code;-

sc.useDelimiter("\\Z")

It’s a java scanner class. This is used to set the delimiting pattern for the Scanner being used. For this case, the Scanner pattern is used. It returns the scanner object.

To better understand, let's take the comparison between BufferedReader, FileReader, and Scanner.

BufferedReader FileReader
It is buffered                                                     It is not buffered
It uses a buffer to read data.                            It reads data from a  file.  
It buffers the character.                                   It obtains characters from a file. 
Comparatively faster                                       Comparatively slower.
More efficient for reading files                       Comparatively less efficient.  
It can read a single character as well as the whole line.    At any given time, just one character can be read.
BufferedReaderScanner
It comes with a bigger buffer memory.It has a smaller buffer memory.
It is synchronous.                                                       It is not synchronous.   
It is comparatively faster.                                           It is comparatively slower. 
It should be used when we are working with multiple threads.                                                              It should be used when we are not working with multiple threads.  
  • Reading the whole file in a List: In Java 7, a convenient method for reading a file as lines of text was added. The method List<String> is used to do so. Bytes from the record are decoded into characters to use the desired charset. This approach guarantees that the record is closed while all bytes had been examined or an I/O error, or different runtime exception, is thrown.

Syntax

public static List readAllLines(Path path, Charset cs)throws IOException
Java Read File

In the above code, we have stored all the data of the file inside a list whose reference variable is read. Apple is the name of our file.

To print the data stored in the list, we have used a while loop, which first iterates over the list and then prints the data inside the list until the list doesn't get empty. When we run the program above, the following is the result we get.

Java Read File
  • Read a text file as String: This is the normal method for reading the entire file as a String in Java, with the caveat that the file must be small or medium in size. Unlike the above method, which stores the whole file data in  List, this method stores all the file's data in a  String.
Java Read File

The above code snippet has implemented the knowledge of reading the text file as a string. Apple is the name of our file, and as you can see from the above code, we have read all the data present inside the file name apple using String. And to print the data from files, we have just printed the String. Following is the result of our code.

Java Read File

Conclusion

As we have mentioned all the methods to read the file in JavaJava, one might get confused to implement. Even though we have mentioned the use case of almost every method, one might be looking for the best way to read a file. Mentioning one method as the best is quite tricky as it varies with what you need and what you are implementing.

While comparing all the file reading methods and analyzing their implementation, we can assume that; the fastest way to read a file is by implementing the concept of BufferedReader. It is fast enough to read millions of lines in a second with its implementation compared to other available methods.


Related Topics

Java float vs double

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

7 minutes read.

Caesar Cipher Program in Java

It is among the most popular and straightforward encryption methods. With this method, each letter in the text is swapped out for a letter that is a certain number of...

3 minutes read.

Multithreading Program in Java

Multithreading Program in Java: Before discussing multithreading, it is important to discuss threads. Threads are the most fundamental part of a process. A process can have one or more threads....

4 minutes read.

Web Crawler in Java

In this article, you will be acknowledged with what a web crawler in java is and what are its functions. You will also be able to understand where to implement...

4 minutes read.

Java file Reader

File Reader: It is used to read the data from files. This class inherits the properties from Input Stream Reader Class. File Reader is for reading characters from the file. Input Stream: Java.io...

4 minutes read.

Java Transient

Java Transient In Java, Serialization is used to convert an object into a stream of the byte. The byte stream consists of the data of the instance as well as the...

3 minutes read.

Hamming Code in Java

In a computer network, hamming code is a unique set of error-correction codes. It is mostly utilised in computer graphics for mistake detection and correction during data transmission from sender...

8 minutes read.

Check whether a Number is a Power of 4 or Not in Java

There are many ways to figure out if an integer is a power of 4. This section will go over a variety of techniques for figuring out whether or not...

11 minutes read.

Java Thread Dump Analyzer

Thread: A thread is a PC program that is stacked into the PC's memory and is under execution. It tends to be executed by a processor or a bunch of processors....

15 minutes read.

Virtual Function in Java

In the Operated Oriented Programming language, a virtual function or virtual method is a collection of functions that overrides the functionality of a function in an inheriting class with the same...

4 minutes read.

Sort Dates in Java

The Collection class's sort() method, which is a component of the Comparator mechanism, arranges the data in decreasing order. The Comparator interface can be used to accomplish the goal while...

4 minutes read.

How to Create Immutable Classes in Java

Introduction Java is a programming language that is entirely object-oriented, and everything in it is seen as an object. And the blueprint or template of these objects are classes. Several classes...

3 minutes read.

Java Integer decode() method

The decode() method of Integer class decodes a String into an Integer. It can accept decimal, hexadecimal and octal numbers. Syntax public static Integer decode(String nm) throws NumberFormatException Parameters The parameter ‘nm’ represents the...

2 minutes read.

Null Pointer Exception in Java

It is a runtime error exception. The null value is allocated to the object reference in this exception. We will explicitly throw this null pointer exception when the program wants...

3 minutes read.

Java Math cosh() Method

The cosh() method of Math class returns the first hyperbolic cosine((e+e)/2) of a double value. Syntax: public static double cosh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic cosine is to be...

2 minutes read.

Java Map Generic

Java arrays maintain an ordered collection of things, and the index can be used to access the data (an integer). Unlike HashMap, which stores data as a Key/Value pair. We...

3 minutes read.

IdentityHashMap in Java

The IdentityHashMap class is comparable to the HashMap class and is an AbstractMap implementation. However, when comparing the key, it uses reference equality rather than object equality (or values). Identity HashMap...

6 minutes read.

How to Convert Timestamp to Date in Java

How to Convert Timestamp to Date in Java You can convert Timestamp to Date by using the constructor of Date class. It returns the long millisecond from Epoch (1st January 1970)...

2 minutes read.

Java DatagramSocket and Java DatagramPacket

Datagrams TCP/IP style networking specifies a serialized, predictable, and reliable stream of data in the form of a packet. Servers and clients communicate through a reliable channel, such as TCP socket, have a dedicated...

6 minutes read.

Package Program in Java

Package Program in Java The package program in Java helps us to understand the significance of packages in Java. Packages are mainly used to group together similar classes, interfaces and sub-packages....

6 minutes read.