In Java, there are multiple ways to read a text file, each suited to different use cases:
1. Using BufferedReader:
Efficient for reading large files line by line.
java
BufferedReader reader = new BufferedReader(new FileReader(“file.txt”));
String line;
while1 != null) {
System.out.println(line);
}
reader.close();
2. Using FileReader:
Reads characters from a file.
java
FileReader fr = new FileReader(“file.txt”);
int i;
while2 != -1) {
System.out.print((char) i);
}
fr.close();
3. Using Scanner:
Useful for reading file content as tokens.
java
Scanner scanner = new Scanner(new File(“file.txt”));
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
4. Using Files class (Java 8+):
Reads all lines into a list.
java
List<String> lines = Files.readAllLines(Paths.get(“file.txt”));
lines.forEach(System.out::println);
Each method offers a balance between simplicity and efficiency, depending on the file size and reading requirements.