π Java Read Files β Efficient File Reading in Java
π§² Introduction β Why File Reading Matters
Reading data from files is a critical part of many Java applicationsβwhether it’s loading configuration settings, importing datasets, or reading logs. Java provides a variety of APIs to read files, from traditional methods like FileReader
to modern approaches like Files.readAllLines()
.
β In this guide, you’ll learn:
- How to read files in Java using different techniques
- When to use
FileReader
,BufferedReader
,Scanner
, orFiles
- How to handle exceptions and resources safely
- Performance tips and best practices for large file reading
π¦ Java File Reading Classes
Class/Method | Use Case |
---|---|
FileReader | Basic character stream reading |
BufferedReader | Efficient reading of text, line by line |
Scanner | Token-based reading (great for parsing) |
Files.readAllLines() | Simple and modern, reads all lines into a list |
Files.lines() | Lazy stream-based reading |
π Read File Using FileReader
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) {
e.printStackTrace();
}
}
}
β Explanation:
- Reads character-by-character
- Suitable for small text files
- Uses try-with-resources to auto-close
π Read File Using BufferedReader
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("example.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
β Explanation:
- Efficient for line-by-line reading
- Avoids character-by-character I/O bottlenecks
- Ideal for reading logs or text files line-by-line
π Read File Using Scanner
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(new File("example.txt"))) {
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
β Explanation:
- Great for parsing numbers, words, tokens
- Use
.hasNext()
,.nextInt()
,.nextDouble()
etc. - More flexible for structured file content
π Read All Lines Using Files.readAllLines()
import java.nio.file.*;
import java.io.IOException;
import java.util.List;
public class FilesReadAllLinesExample {
public static void main(String[] args) throws IOException {
List<String> lines = Files.readAllLines(Paths.get("example.txt"));
lines.forEach(System.out::println);
}
}
β Explanation:
- Reads all lines into a
List<String>
- Simple and modern, but loads entire file into memory
- Suitable for small to medium files
π Stream-based Reading Using Files.lines()
Files.lines(Paths.get("example.txt"))
.filter(line -> !line.isEmpty())
.forEach(System.out::println);
β Explanation:
- Returns a Stream of lines for efficient, lazy processing
- Can filter, map, reduce during reading
π‘ Tip: Always close streams or use try-with-resources
.
π Comparison Table
Method | Best For | Memory Usage | Buffered? | Java Version |
---|---|---|---|---|
FileReader | Small files, character reading | Low | β | 1.0+ |
BufferedReader | Line-by-line reading | Low | β | 1.1+ |
Scanner | Token parsing | Medium | β | 1.5+ |
Files.readAllLines() | Small to mid files | High | β | 1.7+ |
Files.lines() | Large files, streaming processing | Low (streamed) | β | 1.8+ |
π‘ Best Practices
- β
Use
BufferedReader
orFiles.lines()
for large files - β
Always use
try-with-resources
to auto-close readers - β οΈ Avoid
readAllLines()
on large files β memory overload - β
Prefer
Files
API for modern Java apps - π Handle
IOException
andFileNotFoundException
properly
π Summary β Java File Reading Techniques
Java offers flexible file reading methods for different scenarios β whether you need line-by-line efficiency, token-based parsing, or modern stream processing.
π§Ύ Key Takeaways:
- Use
FileReader
andBufferedReader
for traditional reading - Use
Scanner
for parsing structured text - Use
Files.readAllLines()
for simplicity (small files) - Use
Files.lines()
for memory-efficient streaming - Apply
try-with-resources
and exception handling always
βFAQs β Java Read Files
β What is the easiest way to read a file in Java?
Use Files.readAllLines()
for small files or Files.lines()
for large files with stream processing.
β How to read a file line-by-line in Java?
Use BufferedReader.readLine()
inside a loop or Scanner.nextLine()
.
β Which is better: BufferedReader
or Scanner
?
Use BufferedReader
for performance, and Scanner
for parsing tokens like integers or words.
β How to avoid memory issues with large files?
Use Files.lines()
or BufferedReader
, which read line-by-line instead of loading entire content at once.
β Can I read files with UTF-8 encoding?
Yes, use new InputStreamReader(new FileInputStream("file.txt"), StandardCharsets.UTF_8)
or specify charset in Files.newBufferedReader()
.
Share Now :