Introduction
Java provides several ways to read files, ranging from traditional classes in the java.io package to the modern java.nio.file package introduced in Java 7. Each approach has its own advantages and is suitable for different scenarios.
Some of the most commonly used classes for reading files include:
- FileReader
- BufferedReader
- Scanner
- Files
- FileInputStream
Choosing the appropriate method depends on factors such as file size, performance requirements, and the type of data being processed.
Preparing a Sample File
Suppose we have a file named students.txt containing:
Rahul
Amit
Priya
Neha
The following examples will use this file.
Method 1: Reading a File Using FileReader
The FileReader class reads characters from a text file.
Example
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("students.txt");
int character;
while((character = reader.read()) != -1) {
System.out.print((char) character);
}
reader.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
Output
Amit
Priya
Neha
Explanation
- read() reads one character at a time.
- It returns -1 when the end of the file is reached.
- Always close the reader after use.
Method 2: Reading a File Using BufferedReader
BufferedReader is faster because it reads data in larger chunks instead of one character at a time.
Example
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
BufferedReader reader =
new BufferedReader(new FileReader("students.txt"));
String line;
while((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
Output
Amit
Priya
Neha
Advantages
- Faster than FileReader
- Reads one line at a time
- Suitable for large text files
Method 3: Reading a File Using Scanner
The Scanner class is simple and beginner-friendly.
Example
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try {
File file = new File("students.txt");
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} catch(FileNotFoundException e) {
e.printStackTrace();
}
}
}
Output
Amit
Priya
Neha
Advantages
- Easy to use
- Reads lines and tokens
- Good for parsing formatted input
Method 4: Reading a File Using Files.readAllLines()
The Files class is part of the java.nio.file package.
Example
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
List lines =
Files.readAllLines(Paths.get("students.txt"));
for(String line : lines) {
System.out.println(line);
}
}
}
Output
Amit
Priya
Neha
Advantages
- Simple syntax
- Reads the complete file
- Suitable for small and medium-sized files
Method 5: Reading a File Using Files.readString() (Java 11)
Java 11 introduced the readString() method.
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
String content =
Files.readString(Paths.get("students.txt"));
System.out.println(content);
}
}
Output
Amit
Priya
Neha
This method is ideal when you need the entire file as a single String.
Method 6: Reading a Binary File Using FileInputStream
FileInputStream is used for binary files such as images, PDFs, audio files, and videos.
Example
import java.io.FileInputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
FileInputStream input =
new FileInputStream("image.png");
int data;
while((data = input.read()) != -1) {
// Process binary data
}
input.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
Unlike FileReader, FileInputStream works with bytes rather than characters.
| Method | Best For | Reads |
|---|---|---|
| FileReader | Small text files | Characters |
| BufferedReader | Large text files | Lines |
| Scanner | Simple input parsing | Tokens and lines |
| Files.readAllLines() | Small/medium text files | All lines |
| Files.readString() | Java 11+ | Entire file |
| FileInputStream | Binary files | Bytes |
Exception Handling
File reading operations may throw exceptions.
Common exceptions include:
| Exception | Cause |
|---|---|
| FileNotFoundException | File does not exist |
| IOException | General input/output error |
| SecurityException | Permission denied |
Example:
try {
FileReader reader = new FileReader("students.txt");
} catch(IOException e) {
e.printStackTrace();
}
Using try-with-resources (Recommended)
The try-with-resources statement automatically closes resources, even if an exception occurs.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try (BufferedReader reader =
new BufferedReader(new FileReader("students.txt"))) {
String line;
while((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
This approach reduces the risk of resource leaks.
Real-Life Example
Suppose you have a configuration file named config.txt.
server=localhost
port=8080
You can read it using BufferedReader.
BufferedReader reader =
new BufferedReader(new FileReader("config.txt"));
String line;
while((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
Applications commonly read configuration files during startup.
Advantages of Reading Files in Java
- Easy to process stored data
- Supports multiple file formats
- Multiple APIs for different needs
- Efficient handling of large files
- Platform independent
- Rich exception handling support
Common Mistakes
1. Forgetting to Close the File
Incorrect:
FileReader reader = new FileReader("students.txt");
Always close it:
reader.close();
Or use try-with-resources.
2. Ignoring Exceptions
Incorrect:
FileReader reader = new FileReader("students.txt");
Correct:
try {
} catch(IOException e) {
}
3. Using FileReader for Binary Files
Incorrect:
FileReader reader = new FileReader("image.png");
Correct:
FileInputStream input =
new FileInputStream("image.png");
4. Reading Large Files with readAllLines()
Files.readAllLines() loads the entire file into memory, which may not be suitable for very large files.
For large files, prefer BufferedReader.
Best Practices
- Use BufferedReader for large text files.
- Use Scanner for simple parsing tasks.
- Use Files.readString() for small files when using Java 11 or later.
- Always close resources or use try-with-resources.
- Handle exceptions properly.
- Validate file existence before reading.
- Use FileInputStream for binary data.
- Avoid loading huge files entirely into memory unless necessary.
Conclusion
Reading files is a fundamental skill in Java programming and is essential for developing applications that work with stored data. Java offers multiple ways to read files, including FileReader, BufferedReader, Scanner, Files, and FileInputStream, each designed for specific use cases.
For modern Java applications, BufferedReader and the Files API are generally preferred because they provide better performance and cleaner code.