1. Using BufferedReader (Classic Approach)
Basic BufferedReader
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("example.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
System.err.println("Error closing file: " + e.getMessage());
}
}
}
}
BufferedReader with Try-with-Resources (Recommended)
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderTryWithResources {
public static void main(String[] args) {
String filePath = "example.txt";
// Automatic resource management
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
int lineNumber = 1;
while ((line = reader.readLine()) != null) {
System.out.println("Line " + lineNumber + ": " + line);
lineNumber++;
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
}
}
2. Using FileReader Directly
import java.io.FileReader;
import java.io.IOException;
public class FileReaderExample {
public static void main(String[] args) {
try (FileReader reader = new FileReader("example.txt")) {
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
3. Using Scanner
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(new File("example.txt"))) {
// Read line by line
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
// Scanner with different delimiters
class ScannerWithDelimiter {
public static void readCSV() {
try (Scanner scanner = new Scanner(new File("data.csv"))) {
scanner.useDelimiter(","); // Set comma as delimiter
while (scanner.hasNext()) {
String token = scanner.next();
System.out.println("Token: " + token.trim());
}
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
4. Using Files.readAllLines() (Java 7+)
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class FilesReadAllLines {
public static void main(String[] args) {
Path filePath = Paths.get("example.txt");
try {
// Read all lines into a List
List<String> lines = Files.readAllLines(filePath, StandardCharsets.UTF_8);
// Process each line
for (String line : lines) {
System.out.println(line);
}
// Using forEach with method reference
lines.forEach(System.out::println);
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
}
}
5. Using Files.lines() (Java 8+ Streams)
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class FilesLinesStream {
public static void main(String[] args) {
Path filePath = Paths.get("example.txt");
// Using try-with-resources with Stream
try (Stream<String> lines = Files.lines(filePath)) {
// Process with Stream operations
lines.filter(line -> !line.trim().isEmpty()) // Skip empty lines
.map(String::toUpperCase) // Convert to uppercase
.forEach(System.out::println); // Print each line
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
}
}
// More Stream operations
class AdvancedStreamOperations {
public static void processFile(String filename) {
Path filePath = Paths.get(filename);
try (Stream<String> lines = Files.lines(filePath)) {
long nonEmptyLines = lines.filter(line -> !line.trim().isEmpty())
.count();
System.out.println("Non-empty lines: " + nonEmptyLines);
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
6. Using FileInputStream with InputStreamReader
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
public class FileInputStreamExample {
public static void main(String[] args) {
// Specify character encoding
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(
new FileInputStream("example.txt"),
StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
7. Reading File into a Single String
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class ReadWholeFile {
public static void main(String[] args) {
Path filePath = Paths.get("example.txt");
try {
// Read entire file as a single string
String content = new String(Files.readAllBytes(filePath));
System.out.println(content);
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
8. Practical Examples with Error Handling
Complete File Reader Utility Class
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
public class FileReaderUtility {
// Read file and return List of lines
public static List<String> readFileAsList(String filename) {
List<String> lines = new ArrayList<>();
Path filePath = Paths.get(filename);
if (!Files.exists(filePath)) {
System.err.println("File does not exist: " + filename);
return lines;
}
try (BufferedReader reader = Files.newBufferedReader(filePath, StandardCharsets.UTF_8)) {
String line;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
} catch (IOException e) {
System.err.println("Error reading file " + filename + ": " + e.getMessage());
}
return lines;
}
// Read file and return single string
public static String readFileAsString(String filename) {
try {
return new String(Files.readAllBytes(Paths.get(filename)));
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
return "";
}
}
// Count lines in file
public static long countLines(String filename) {
Path filePath = Paths.get(filename);
try (Stream<String> lines = Files.lines(filePath)) {
return lines.count();
} catch (IOException e) {
System.err.println("Error counting lines: " + e.getMessage());
return 0;
}
}
// Find lines containing specific text
public static List<String> findLinesContaining(String filename, String searchText) {
List<String> matchingLines = new ArrayList<>();
Path filePath = Paths.get(filename);
try (Stream<String> lines = Files.lines(filePath)) {
lines.filter(line -> line.toLowerCase().contains(searchText.toLowerCase()))
.forEach(matchingLines::add);
} catch (IOException e) {
System.err.println("Error searching file: " + e.getMessage());
}
return matchingLines;
}
}
Using the Utility Class
public class FileReaderDemo {
public static void main(String[] args) {
String filename = "data.txt";
// Read as list
List<String> lines = FileReaderUtility.readFileAsList(filename);
System.out.println("Total lines: " + lines.size());
// Read as string
String content = FileReaderUtility.readFileAsString(filename);
System.out.println("File content:\n" + content);
// Count lines
long lineCount = FileReaderUtility.countLines(filename);
System.out.println("Line count: " + lineCount);
// Search for specific text
List<String> results = FileReaderUtility.findLinesContaining(filename, "error");
System.out.println("Lines containing 'error': " + results.size());
}
}
9. Reading Files from Resources Folder
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
public class ReadFromResources {
public void readResourceFile() {
// For files in src/main/resources
try (InputStream inputStream = getClass().getClassLoader()
.getResourceAsStream("config.properties");
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("Error reading resource file: " + e.getMessage());
} catch (NullPointerException e) {
System.err.println("Resource file not found");
}
}
}
10. Performance Comparison
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
public class PerformanceComparison {
public static void main(String[] args) {
String filename = "largefile.txt";
long startTime, endTime;
// Method 1: BufferedReader
startTime = System.currentTimeMillis();
readWithBufferedReader(filename);
endTime = System.currentTimeMillis();
System.out.println("BufferedReader: " + (endTime - startTime) + "ms");
// Method 2: Files.readAllLines
startTime = System.currentTimeMillis();
readWithFilesReadAllLines(filename);
endTime = System.currentTimeMillis();
System.out.println("Files.readAllLines: " + (endTime - startTime) + "ms");
// Method 3: Files.lines with Stream
startTime = System.currentTimeMillis();
readWithFilesLines(filename);
endTime = System.currentTimeMillis();
System.out.println("Files.lines: " + (endTime - startTime) + "ms");
// Method 4: Scanner
startTime = System.currentTimeMillis();
readWithScanner(filename);
endTime = System.currentTimeMillis();
System.out.println("Scanner: " + (endTime - startTime) + "ms");
}
private static void readWithBufferedReader(String filename) {
try (BufferedReader br = Files.newBufferedReader(Paths.get(filename))) {
while (br.readLine() != null) {
// Just reading, no processing
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void readWithFilesReadAllLines(String filename) {
try {
Files.readAllLines(Paths.get(filename));
} catch (IOException e) {
e.printStackTrace();
}
}
private static void readWithFilesLines(String filename) {
try {
Files.lines(Paths.get(filename)).count(); // Count lines
} catch (IOException e) {
e.printStackTrace();
}
}
private static void readWithScanner(String filename) {
try (Scanner scanner = new Scanner(Paths.get(filename))) {
while (scanner.hasNextLine()) {
scanner.nextLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Best Practices Summary
- Use Try-with-Resources - Always use for automatic resource management
- Specify Character Encoding - Use UTF-8 for consistent behavior
- Handle Exceptions Properly - Don't swallow exceptions
- Choose the Right Method:
- Use
Files.readAllLines()for small files - Use
BufferedReaderorFiles.lines()for large files - Use
Scannerfor formatted input
- Check File Existence - Validate files before reading
- Close Resources - Use try-with-resources to ensure proper closure
Common File Paths
import java.nio.file.Paths;
public class FilePaths {
public static void main(String[] args) {
// Relative path (from current working directory)
String relativePath = "data/file.txt";
// Absolute path
String absolutePath = "C:/Users/Name/documents/file.txt";
// Using Paths.get() - platform independent
var path1 = Paths.get("data", "file.txt"); // data/file.txt
var path2 = Paths.get("/home", "user", "file.txt"); // /home/user/file.txt
// Current directory
var currentDir = Paths.get("").toAbsolutePath();
System.out.println("Current directory: " + currentDir);
}
}
This comprehensive guide covers all major approaches to reading text files in Java, from basic to advanced techniques, with proper error handling and best practices.