-
Hajipur, Bihar, 844101
After learning how to create and write files in Java, the next step is to read files. Reading files allows your program to access saved data, display it to users, or use it for processing. Whether you’re reading a text file, a configuration file, or large data logs, Java provides several easy-to-use classes for this purpose.
In this tutorial, you’ll learn how to read files in different ways using both the traditional java.io package and the modern java.nio.file package.
File reading is an essential part of any real-world Java program. For example:
A text editor reads files that users open.
A configuration system reads settings stored in a file.
A data analysis tool reads CSV files for processing.
Reading files helps you retrieve stored information and use it again without entering it manually every time.
Java provides several approaches to read data from files. The most common ones are:
Using FileReader and BufferedReader
Using Scanner
Using FileInputStream
Using Files.readAllLines() or Files.readString() (from NIO)
Each approach serves a slightly different purpose. Let’s look at them one by one.
FileReader is the simplest class for reading character data from files. It reads one character at a time, so it’s better suited for smaller files.
Example:
import java.io.FileReader;
import java.io.IOException;
public class FileReaderExample {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("notes.txt");
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
reader.close();
} catch (IOException e) {
System.out.println("An error occurred while reading the file.");
e.printStackTrace();
}
}
}
How it works:
The read() method reads one character at a time and returns -1 when it reaches the end of the file.
You must close the reader after reading to release system resources.
If your file is large or you want to read it line by line, BufferedReader is a better choice. It reads data efficiently by storing chunks of characters in memory.
Example:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new FileReader("log.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
System.out.println("Error reading file.");
e.printStackTrace();
}
}
}
Explanation:
The readLine() method reads one full line at a time until there are no more lines.
This approach is ideal for reading text files line by line, such as logs or CSV files.
The Scanner class is another simple and flexible way to read files. It allows you to read line by line or even word by word.
Example:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
try {
File file = new File("data.txt");
Scanner reader = new Scanner(file);
while (reader.hasNextLine()) {
String line = reader.nextLine();
System.out.println(line);
}
reader.close();
} catch (FileNotFoundException e) {
System.out.println("File not found.");
e.printStackTrace();
}
}
}
Why use Scanner?
It’s easy to use and offers multiple methods like nextLine(), nextInt(), and nextDouble() to read different data types.
You can use it for structured data or formatted input.
If you want to read binary files (images, audio, PDFs, etc.) or work with raw bytes, you can use FileInputStream.
Example:
import java.io.FileInputStream;
import java.io.IOException;
public class FileInputStreamExample {
public static void main(String[] args) {
try {
FileInputStream input = new FileInputStream("example.txt");
int data;
while ((data = input.read()) != -1) {
System.out.print((char) data);
}
input.close();
} catch (IOException e) {
System.out.println("Error reading the file.");
e.printStackTrace();
}
}
}
This approach reads the file as a sequence of bytes and converts them into characters if needed.
The java.nio.file package introduced in Java 7 provides a modern and more convenient way to read files. You can use Files.readAllLines() to read the entire file into a list of strings.
Example:
import java.nio.file.*;
import java.io.IOException;
import java.util.List;
public class NioReadExample {
public static void main(String[] args) {
Path path = Paths.get("niofile.txt");
try {
List<String> lines = Files.readAllLines(path);
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Error reading file.");
e.printStackTrace();
}
}
}
Benefits:
Reads the entire file at once.
Very concise and clean.
Ideal for small to medium-sized text files.
If you’re using Java 11 or higher, you can read an entire file as a single string using Files.readString().
Example:
import java.nio.file.*;
import java.io.IOException;
public class ReadStringExample {
public static void main(String[] args) {
Path path = Paths.get("sample.txt");
try {
String content = Files.readString(path);
System.out.println(content);
} catch (IOException e) {
System.out.println("Error reading the file.");
e.printStackTrace();
}
}
}
This is one of the simplest and most readable ways to read a complete text file.
File reading operations often fail due to missing files, permission issues, or incorrect paths. Always handle exceptions such as:
FileNotFoundException – When the file doesn’t exist.
IOException – For general input/output errors.
It’s also a good practice to use try-with-resources, which automatically closes the file after reading:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TryWithResourcesExample {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("auto.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Error reading file.");
e.printStackTrace();
}
}
}
Always close your file reader – This prevents resource leaks.
Use buffering for large files – BufferedReader improves performance.
Use Scanner for structured text – Ideal for formatted or space-separated data.
Use NIO for modern, clean code – The Files class simplifies file operations.
Handle exceptions carefully – Always use meaningful messages and logs.
Reading files in Java is flexible and simple once you know the right classes to use.
Use FileReader or BufferedReader for basic text reading.
Use Scanner for structured or line-by-line reading.
Use FileInputStream for binary data.
Use Files.readAllLines() or Files.readString() for a modern approach.
In the next tutorial, we’ll learn how to delete files safely and handle possible errors during deletion.
Write a Java program using FileReader to read and print the contents of a file named notes.txt character by character.
Create a program using BufferedReader that reads a file called data.txt line by line and prints each line with its line number.
Write a Java program using Scanner to read a file named students.txt and display its content line by line.
Write a Java program that reads a file called details.txt using BufferedReader and counts how many lines the file contains.
Write a program using FileInputStream that reads a text file and displays its content as a string on the console.
Write a Java program using the NIO method Files.readAllLines() to read a file named report.txt and print all lines in uppercase.
Write a program using Files.readString() (Java 11+) to read the content of a file named summary.txt and display its total character count.
Write a Java program that reads a file using Scanner and counts how many words are present in it.
Write a Java program using a try-with-resources statement with BufferedReader to safely read the contents of a file named auto.txt.
Write a Java program that handles the FileNotFoundException by displaying a user-friendly message when trying to read a missing file.