How to read the contents of a TXT file in Java?
We can use FileReader and BufferedReader from Java IO package to read the contents of a txt file in Java. Here is a simple example:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class ReadTextFile {
public static void main(String[] args) {
File file = new File("example.txt"); // 替换为你的txt文件路径
try (FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr)) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
In the code above, we first create a File object specifying the path of the txt file to be read. Then, we open the file using FileReader and BufferedReader to read the contents line by line until reaching the end of the file. After reading each line, we print it to the console.
Please replace the “example.txt” in the above code with the path to the txt file you want to read, and then run the program to read the content of the txt file.