Different ways of Reading a text file in Java
Last Updated :
04 Jan, 2025
There are multiple ways of writing and reading a text file in Java. this is required while dealing with many applications. There are several ways to read a plain text file in Java e.g. you can use FileReader, BufferedReader, or Scanner to read a text file. Every utility provides something special e.g. BufferedReader provides buffering of data for fast reading, and Scanner provides parsing ability.
Methods for Reading a Text File
- Using BufferedReader class
- Using Scanner class
- Using File Reader class
- Reading the whole file in a List
- Read a text file as String
Note: We can also use both BufferReader and Scanner to read a text file line by line in Java. Then Java SE 8 introduces another Stream class java.util.stream.Stream which provides a lazy and more efficient way to read a file.
Let us discuss each of the above methods to a deeper depth and most importantly by implementing them via a clean java program.
1. BufferedReader Class for Reading text file
This method reads text from a character-input stream. It does buffer for efficient reading of characters, arrays, and lines. The buffer size may be specified, or the default size may be used. The default is large enough for most purposes. In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders as shown below as follows:
Syntax
BufferedReader in = new BufferedReader(Reader in, int size);
Example
Java
// Java Program to illustrate Reading from FileReader
// using BufferedReader Class
import java.io.*;
public class UsingBufferReader
{
public static void main(String[] args) throws Exception
{
// Creating BufferedReader for Input
BufferedReader bfri = new BufferedReader(
new InputStreamReader(System.in));
System.out.print("Enter the Path : ");
// Reading File name
String path; = bfri.readLine();
// Note: Double backquote is to avoid compiler
// interpret words
// like \test as \t (ie. as a escape sequence)
// Creating an object of BufferedReader class
BufferedReader bfro = new BufferedReader(
new FileReader(path));
// Declaring a string variable
String st;
// Condition holds true till
// there is character in a string
while ((st = bfro.readLine()) != null)
System.out.println(st);
}
}
Output

2. FileReader class for Reading text file
Convenience class for reading character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate.
Constructors defined in this class are as follows:
- FileReader(File file): Creates a new FileReader, given the File to read from
- FileReader(FileDescriptor fd): Creates a new FileReader, given the FileDescriptor to read from
- FileReader(String fileName): Creates a new FileReader, given the name of the file to read from
Example
Java
// Java Program to Illustrate reading from
// FileReader using FileReader class
// Importing input output classes
import java.io.*;
// Main class
// ReadingFromFile
public class UsingFileReader {
// Main driver method
public static void main(String[] args) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the Path : ");
// Reading File name
String path = br.readLine();
FileReader fr = new FileReader(path);
// Declaring loop variable
int i;
// Holds true till there is nothing to read
while ((i = fr.read()) != -1)
// Print all the content of a file
System.out.print((char)i);
}
}
Output

3. Scanner class for reading text file
A simple text scanner that can parse primitive types and strings using regular expressions. A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
Example 1: With using loops
Java
// Java Program to illustrate
// reading from Text File
// using Scanner Class
import java.io.*;
import java.util.Scanner;
public class UsingScannerClass
{
public static void main(String[] args) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the Path : ");
// Reading File name
String path = br.readLine();
// pass the path to the file as a parameter
File file = new File(path);
Scanner sc = new Scanner(file);
while (sc.hasNextLine())
System.out.println(sc.nextLine());
}
}
Output

Example 2: Without using loops
Java
// Java Program to illustrate reading from FileReader
// using Scanner Class reading entire File
// without using loop
import java.io.*;
import java.util.Scanner;
public class ReadingEntireFileWithoutLoop {
public static void main(String[] args)
throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the Path : ");
// Reading File name
String path = br.readLine();
File file = new File(path);
Scanner sc = new Scanner(file);
// we just need to use \\Z as delimiter
sc.useDelimiter("\\Z");
System.out.println(sc.next());
}
}
Output

4. Reading the whole file in a List
Read all lines from a file. This method ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown. Bytes from the file are decoded into characters using the specified charset.
Syntax:
public static List readAllLines(Path path,Charset cs)throws IOException
This method recognizes the following as line terminators:
\u000D followed by \u000A, CARRIAGE RETURN followed by LINE FEED
\u000A, LINE FEED
\u000D, CARRIAGE RETURN
Example
Java
// Java program to illustrate reading data from file
// using nio.File
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
public class ReadFileIntoList
{
public static List<String> readFileInList(String fileName)
{
// Created List of String
List<String> lines = Collections.emptyList();
try {
lines = Files.readAllLines(
Paths.get(fileName),
StandardCharsets.UTF_8);
} catch(IOException e) {
// do something
e.printStackTrace();
}
return lines;
}
// Main method
public static void main(String[] args)
throws IOException
{
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the Path : ");
// Reading File name
String path = br.readLine();
List l = readFileInList(path);
// Iterator iterating over List
Iterator<String> itr = l.iterator();
while (itr.hasNext())
System.out.println(itr.next());
}
}
Output

5. Read a text file as String
Example:
Java
// Java Program to illustrate
// reading from text file
// as string in Java
package io;
import java.nio.file.*;
public class ReadTextAsString {
public static String readFileAsString(String fileName)
throws Exception
{
String data = "";
data = new String(
Files.readAllBytes(Paths.get(fileName)));
return data;
}
public static void main(String[] args) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the Path : ");
// Reading File name
String path = br.readLine();
String data = readFileAsString(path);
System.out.println(data);
}
}
Output
Similar Reads
Different Ways to Copy Files in Java
There are mainly 3 ways to copy files using java language. They are as given below: Using File Stream (Naive method)Using FileChannel ClassUsing Files class. Note: There are many other methods like Apache Commons IO FileUtils but we are solely discussing copying files using java classes. Method 1: U
5 min read
Ways to Read Input from Console in Java
In Java, there are four different ways to read input from the user in the command line environment(console). 1. Using Buffered Reader ClassBuffered Reader Class is the classical method to take input, Introduced in JDK 1.0. This method is used by wrapping the System.in (standard input stream) in an I
5 min read
Java program to delete certain text from a file
Prerequisite : PrintWriter , BufferedReader Given two files input.txt and delete.txt. Our Task is to perform file extraction(Input-Delete) and save the output in file say output.txt Example : Naive Algorithm : 1. Create PrintWriter object for output.txt 2. Open BufferedReader for input.txt 3. Run a
3 min read
BufferedReader readLine() method in Java with Examples
The readLine() method of BufferedReader class in Java is used to read one line text at a time. The end of a line is to be understood by '\n' or '\r' or EOF. Syntax: public String readLine() throws IOException Parameters: This method does not accept any parameter. Return value: This method returns th
2 min read
Different Ways to Generate String by using Characters and Numbers in Java
Given a number num and String str, the task is to generate the new String by extracting the character from the string by using the index value of numbers. Examples: Input: str = âGeeksforGeeksâ num = 858 Output: GfG Explanation: The 8th, 5th, and 8th position of the characters are extracting from th
3 min read
Difference Between FileInputStream and ObjectInputStream in Java
FileInputStream class extracts input bytes from a file in a file system. FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader. It should be used to read byte-oriented data for example to read audio, video, images,
5 min read
StringReader read(CharBuffer) method in Java with Examples
The read(CharBuffer) method of StringReader Class in Java is used to read the specified characters into a CharBuffer instance. This method blocks the stream till: It has taken some input from the stream. Some IOException has occurred It has reached the end of the stream while reading. Syntax: public
2 min read
Encrypt and Decrypt String File Using Java
In the field of cryptography, encryption is the process of turning plain text or information into ciphertext, or text that can only be deciphered by the intended recipient. A cipher is a term used to describe the encryption algorithm. It secures communication networks and aids in preventing illegal
3 min read
Difference between next() and nextLine() methods in Java
The Scanner class in java.util package used for obtaining the input of the primitive types like int, double, etc. and strings. It is the easiest way to read input in a Java program, though not very efficient if you want an input method for scenarios where time is a constraint like in competitive pro
3 min read
Reader read(CharBuffer) method in Java with Examples
The read(CharBuffer) method of Reader Class in Java is used to read the specified characters into a CharBuffer instance. This method blocks the stream till: It has taken some input from the stream. Some IOException has occurred It has reached the end of the stream while reading. Syntax: public int r
2 min read