×

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 Throw and Throws Keyword

Exceptions in Java enable us to construct high-quality programs where faults are checked at compile time rather than run time and where we may define unique exceptions that make code...

6 minutes read.

Difference between C, C++, java

C Language: C language is a procedure oriented language. It has been invented by Dennis Ritchie in the year 1970. It is one of the computer programming language. The purpose of...

3 minutes read.

ConcurrentSkipListSet in Java

ConcurrentSkipListSet is a class that is a part of collection framework in Java.It has been available since Java version 1.6. ConcurrentSkipListSet  is a scalable concurrent NavigableSet implementation based on a ConcurrentSkipListMap.The...

16 minutes read.

What is new in Java 17?

Java 17 LTS is the most recent long-term support release for the Java SE platform. Under the Oracle No-Fee Terms and Conditions License, which stands for long-term support, JDK 17...

6 minutes read.

Java Math log10() Method

The log10() method of Math class returns the base 10 logarithmic value for the specified double argument. Syntax: public static double log10(double a) Parameters: The parameter ‘a’ represents a double value. Return Value: The log10() method...

2 minutes read.

Java File

Java file class implements the concept of file handling. It has several methods, such as deleting, creating, reading, and updating files. This class allows java users to perform various operations...

5 minutes read.

Java Integer toUnsignedLong() method

The toUnsignedLong() method of Java Integer class returns a long value by simply converting the given argument to long after an unsigned conversion. Syntax public static long toUnsignedLong (int  x) Parameters The parameter ‘x’...

1 minute read.

Java 8 Features

Java 8 Features: After the great success of Java 7, many developers were waiting for the next version of one of the best languages in the tech world. Moreover, on...

6 minutes read.

Ganesha’s Pattern in Java

This part teaches us how to use stars and other special characters to write Ganesha's Pattern in Java programming. Among the most challenging Java pattern applications to code. The Ganesha will be...

3 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.

Java vs DotNET

Before understanding the differences between DotNET and Java, one must know about Java and DotNET. Java Java is a general-purpose programming language that is class-based and object-oriented, with minimal implementation dependencies. Regardless of...

9 minutes read.

How to take Array Input in Java

In this tutorial, we will learn about how to take array input in Java. So, before taking inputs let us know what an array is first. Array: An array is a collection...

10 minutes read.

Mutable and Immutable in Java

Java is a programming language in which everything is treated as an object. Its procedures and functions are centred around objects because it is an object-oriented programming language. Mutable and...

6 minutes read.

Conditional operator in Java

In Java, there are around eight operators, and among them, three operators are used to evaluate the condition and decide the Result based on the Result of the evaluated condition. Below...

4 minutes read.

JRE (Java Runtime Environment)

JRE is an installation package that provides an environment to run the Java program on any Operating System. It does not deal with the development process of any application. It is a part...

2 minutes read.

Scanner in Java

Static way of Programming: When a variable can’t change its value during run time is called a Static way of programming. In this programming a variable is directly assigned to a...

4 minutes read.

Java File Extension

A computer file's suffix is called its file extension. It is easily recognized since it appears immediately after a period (.) in the file name. Consider the file Demo.java as an...

3 minutes read.

Java Switch Keyword

In this article we are going to learn the concept of a java switch keyword. Generally, java case keyword is used with the switch statements or keyword.Switch keyword is implemented in...

3 minutes read.

Difference between String Tokenizer and split Method in Java

Introduction Today, let us understand the difference between String Tokenizer and Split Method. First, let us learn about the String Tokenizer and Split method individually and then know about their differences String...

7 minutes read.

Web Service Response Time Calculation in Java

Administration response time or reaction time is the typical measure of time it takes for a solicitation to be handled by a PC framework, like your organization switch. In the...

4 minutes read.