To read a plain text file in Java, you can use various approaches. Below are some commonly used methods with examples:
1. Using BufferedReader
This is a simple and efficient way to read a text file line by line.
Code Example:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFileExample {
public static void main(String[] args) {
String filePath = "example.txt"; // Replace with your file path
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while1 != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
- Explanation:
FileReader
reads the file character by character.BufferedReader
improves performance by buffering the input and allows reading the file line by line withreadLine()
.
2. Using Files
Class (Java NIO)
The Files
class provides modern and concise methods to read the entire file content at once.
Code Example:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class ReadFileExample {
public static void main(String[] args) {
String filePath = "example.txt"; // Replace with your file path
try {
List<String> lines = Files.readAllLines(Paths.get(filePath));
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
- Explanation:
Files.readAllLines()
reads the file into aList
of strings, where each string represents a line in the file.- Suitable for small to medium-sized files.
3. Using Scanner
Class
Scanner
is another simple way to read a file, commonly used for reading structured data.
Code Example:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFileExample {
public static void main(String[] args) {
String filePath = "example.txt"; // Replace with your file path
try (Scanner scanner = new Scanner(new File(filePath))) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
- Explanation:
Scanner
reads the file line by line usinghasNextLine()
andnextLine()
.- Suitable for parsing and processing text line by line.
4. Using FileInputStream
and InputStreamReader
This method is useful for reading files with a specific character encoding.
Code Example:
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
public class ReadFileExample {
public static void main(String[] args) {
String filePath = "example.txt"; // Replace with your file path
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8"))) {
String line;
while1 != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
- Explanation:
- Use
InputStreamReader
to specify the character encoding (e.g., UTF-8). - Suitable for files with non-default encodings.
- Use
5. Using Files.lines()
(Java 8 and Above)
This approach streams the file lines for efficient processing, especially for large files.
Code Example:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.stream.Stream;
public class ReadFileExample {
public static void main(String[] args) {
String filePath = "example.txt"; // Replace with your file path
try (Stream<String> lines = Files.lines(Paths.get(filePath))) {
lines.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
}
- Explanation:
Files.lines()
creates a stream of lines from the file.- Ideal for processing large files efficiently.
6. Reading Entire File as a String
If you want to read the entire file content into a single String
:
Code Example:
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
public class ReadFileExample {
public static void main(String[] args) {
String filePath = "example.txt"; // Replace with your file path
try {
String content = new String(Files.readAllBytes(Paths.get(filePath)));
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
}
}
- Explanation:
Files.readAllBytes()
reads all the bytes from the file into abyte[]
, which is then converted to aString
.
Best Practices
- Close Resources: Always use
try-with-resources
to automatically close file-related resources. - Exception Handling: Handle exceptions properly to avoid runtime errors.
- Character Encoding: Be mindful of the file’s encoding to avoid issues with special characters.