×

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

How to Convert double to int in Java

The double is a larger data type than int. When we assign a larger type value to a variable of smaller type, then we need to perform the explicit conversion....

2 minutes read.

How to Develop Programming Logic in Java?

Introduction In the world of software development, Java programming language is one of the most powerful programming languages that is used to create a wide range of applications. It includes desktop,...

18 minutes read.

Alice and Bob Problem Java

Alice and Bob were two friends who liked to play games. Both together found a game, which has the description below. The game begins with an integer num, used to create...

2 minutes read.

Duodecimal in Java

Duodecimal is a notation style in which a number with a base of 12 is referred to be a duodecimal number. In Java, we can use to convert duodecimal integers...

2 minutes read.

Char and String differences in Java

Characters in Java Character (char) belongs to the characters group, which represents symbols in a character set, such as alphabets and numerals. A Java char has 16 bits in length and has a range...

5 minutes read.

Java program to find frequency of characters in a string

In this article, you will understand the how to find the frequency of characters in strings by using Java programming language. Along with this, you will understand the hashing concept...

3 minutes read.

Calculator Program in Java

Calculator Program in Java A calculator performs the basic mathematical operations such as addition, subtraction, multiplication, etc. In this section, we will create a calculator program in Java using switch case...

5 minutes read.

How to create array of objects in Java

Java is an object-oriented programming language therefore everything in Java is based on objects and classes. Array is a data structure that holds data of similar type and dynamically creates...

4 minutes read.

Java Rename File

Renaming a file is the process of changing its name. Using the renameTo() function of the Java File class, renaming operations are possible. A file can be renamed using Java's renameTo()...

3 minutes read.

Anagram Program in Java using String

Anagram Program in Java Anagrams are those words that are generated by rearrangement of the letters of another phrase or word. Usually, while doing the rearrangement, the original letters are used...

8 minutes read.

Cosmic Superclass in Java

The parent class of all Java classes is the Object class. The Java Object class is the parent of all Java classes, whether directly or indirectly. The Object class is...

6 minutes read.

Merge Sort in Java

Merge Sort in Java Merge sort in Java uses the divide and conquer approach to sort the given array/ list. There are three steps involved in the merge sort. 1) Divide the...

5 minutes read.

GCD Program in Java

GCD Program in Java The GCD program in Java outputs the GCD of the given numbers. In mathematics, Greatest Common Divisor (GCD), Greatest Common Factor or Highest Common Factor (HCF) of...

14 minutes read.

How to Create a Package in Java?

For the most part, how to create a package in Java generally, a package is defined as a collection of relevant or irrelevant items together in a very major way....

7 minutes read.

AES 256 Encryption in Java

Now a days, security has grown in importance. Java programming supports a variety of encryption and hashing methods, which offers security for data transport and communication among various nodes. In...

4 minutes read.

Java Boolean compareTo() method

The compareTo() method of Java Boolean class compares the Boolean argument with the Boolean instance and returns integer value, zero, or negative 1, or positive 1 based on the result...

2 minutes read.

Java Coding Software

Desktop and web apps are created using Java, an object-oriented programming language. Java code may be executed on any platform, making it platform-independent. A text editor, tool, or piece of...

9 minutes read.

Java StringWriter Class

The StringWriter class is a character stream in which it is used to store the output consisting of characters into the string buffer. Upon collecting output into a string buffer,...

3 minutes read.

Array and String based questions in Java

1. What is an Array in Java? A collection of identical data types is referred to as an array. There can be no separate data kinds. It supports the storage of...

4 minutes read.

Java Math ceil() Method

The ceil() method of Math class returns the smallest double value which is closest to negative infinity and is greater than or equal to the argument. Syntax: public static double ceil(double a) Parameters: The...

2 minutes read.