How to Read Text File in Java
In this tutorial, we will learn how to read data (or text) of a file using various classes in Java. There are several ways to read a text file in Java.
By using the following classes, we can read data from any text file in Java easily. They are as:
- BufferedInputStream class
- BufferedReader class
- Scanner class
- FileReader class
- Reading the entire file in a list using readAllLines() of Files class
- Read a text file as String
Let’s understand easy ways to read data from a file in Java with example programs.
Reading Text File in Java using BufferedInputStream
BufferedInputStream in Java is a concrete subclass of FilterInputStream class. It wraps (buffers) an input stream into a buffered stream and makes read operations on the stream more efficient and fast.
In other words, BufferedInputStream adds buffering capabilities to an input stream that stores data (in bytes) temporarily into a memory buffer by reading from the stream.
It adds an additional layer of functionality around the underlying stream. Therefore, it speeds up the input by reducing the number of disk or file reads.
Let’s create a simple Java program to read data from a file myfile.txt line by line using BufferedInputStream class. Look at the example code to understand better.
Example 1:
package javaProgram;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
public class ReadFile {
public static void main(String[] args)
{
try {
// Create a FileInputStream object to attach myfile to FileInputStream.
FileInputStream fis = new FileInputStream("D:\\myfile.txt");
// Create a BufferedInputStream object to wrap FileInputStream in BufferedInputStream.
BufferedInputStream bis = new BufferedInputStream(fis);
int i = 0;
while ((i = bis.read()) != -1) {
char ch = (char)i;
System.out.print(ch);
}
bis.close();
fis.close();
} catch(Exception e)
{
System.out.println(e);
}
}
}
Output: First Line Second Line Third Line Fourth Line
In this example program,
1. We have created a buffered input stream named bis and connected it to FileInputStream fis.
2. Then, we have used a while loop and read() method to read all bytes from the internal buffer and display them on the console. Here, we assume that you have the following data in “myfile.txt” file:
First Line Second Line Third Line Fourth Line
Read Text File in Java line by line using BufferedReader
BufferedReader in Java is a buffering input character stream that reads text from the buffer rather than directly underlying input stream or other text sources.
It adds the buffering capability to the underlying input character stream, so that there is no need to access the underlying file system for each read and write operation.
BufferedReader is a subclass of the Reader class that extends Object class. It implements Closeable, AutoCloseable, and Readable interfaces. It is also a superclass of LineNumberReader class.
Let’s create a Java program in which we will read a text of line from an existing file and display it on the console.
Example 2:
package javaProgram;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
public static void main(String[] args) throws IOException
{
String filepath = "D:\\myfile.txt";
// Create an object of FileReader and pass filepath to its constructor.
FileReader fr = new FileReader(filepath);
// Create an object of BufferedReader and pass FileReader fr to its constructor.
BufferedReader br = new BufferedReader(fr);
String lineOfText;
// Read a line of text.
while((lineOfText = br.readLine()) != null)
{
System.out.println(lineOfText);
}
}
}
Output: First Line Second Line Third Line Fourth Line
Assume that you have the following data in the myfile.txt file:
First Line Second Line Third Line Fourth Line
Best Way to Read Text File in Java using Scanner class
Scanner in Java is a pre-defined class that reads or scans the data dynamically from the keyboard or a text file. In other words, Scanner class allows the user to read all types of numeric values, strings, and other types of data in Java, whether it comes from a disk file, keyboard, or another source.
It is the fastest and easiest way to receive the input from the user in java than InputStreamReader and BufferedReader.
Let’s take a simple example program where we will read data from the myfile.txt file using Scanner class.
Example 3:
package javaProgram;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) throws IOException
{
// Create an object of File class.
File file = new File("D:\\myfile.txt");
// Create an object of Scanner class for the file.
Scanner sc = new Scanner(file);
// Reading data from the file.
while (sc.hasNext())
{
String firstName = sc.next();
String mName = sc.next();
String lastName = sc.next();
int age = sc.nextInt();
System.out.println(firstName + " " + mName + " " + lastName + " " + age);
}
// Close the file
sc.close();
}
}
Output: John T Smith 50 Eric K Smith 45
Data written into the text file is as:
John T Smith 50 Eric K Smith 45
In this program, each iteration in the while loop reads the first name, middle name, last name, and age from the text file. The file is closed using close() method. It is not essential to close the input file, but it is a good practice to do so to release the resources occupied by the file.
Reading Text File in Java using FileReader class
FileReader in Java is an input stream that reads data in the form of characters from a text file. In other words, FileReader is a character-based input stream that is used to read characters from a file.
FileReader class is a subclass of InputStreamReader class that extends Reader class. It implements Closeable, AutoCloseable, and Readable interfaces.
To read text file line by line in Java using FileReader class, go to this tutorial: FileReader class in Java
Reading Entire Content of a File using Files class
The Files class provides a static method named readAllLines() to read the contents of a file as lines of text. The readAllLines() method comes into two variants. The general signature of this method is as:
static List<String> readAllLines(Path path)
static List<String> readAllLines(Path path, Charset cs)
Both methods may throw an IOException. They use a carriage return, a line feed, and a carriage returned followed by a line feed as a line terminator.
Let’s create a Java program to read whole contents of a file using readAllLines() method of Files class.
Example 4:
package javaProgram;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public class ReadAllLines {
public static List readFile(String fileName)
{
List lines = Collections.emptyList();
try {
// Read all lines and return a list of string.
lines = Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);
}
catch (IOException e) {
e.printStackTrace();
}
return lines;
}
public static void main(String[] args) throws IOException
{
List list = readFile("D://myfile.txt");
// Print each line using iterator() method.
Iterator itr = list.iterator();
while (itr.hasNext())
System.out.println(itr.next());
}
}
Output: This is the first line. This is the second line. This is the third line. This is the fourth line.
Assume that you have the following contents written in the text file, is as:
This is the first line. This is the second line. This is the third line. This is the fourth line.
Read a Text File as String
Let’s create a Java program to read a text file as string. In this program, we will use readAllBytes() method of Files class. The readAllBytes() method of Files class reads the contents of a file as bytes. The general syntax of this method is as:
static byte[ ] readAllBytes(Path path)
This method ensures that the file is closed when all bytes have read or I/O error, or other runtime exception is thrown.
Example 5:
package javaProgram;
import java.nio.file.Files;
import java.nio.file.Paths;
public class ReadTextAsString {
public static String readFile(String fileName)throws Exception
{
String fileContents = "";
fileContents = new String(Files.readAllBytes(Paths.get(fileName)));
return fileContents;
}
public static void main(String[] args) throws Exception
{
String fileContents = readFile("D://myfile.txt");
System.out.println(fileContents);
}
}
Output: This is the first line. This is the second line.
In this tutorial, you have learned how to read text file in Java using various classes with examples. I hope that you will have understood all the basic points related to reading text file and practiced all example programs. In the next, you will learn how to create a text file in Java.
Please email us if you find anything inaccurate, or you want to share more information about the topic discussed above.
Thanks for reading!!!