How can Java read file content in real time?
In Java, you can use the BufferedReader class to read file content in real-time. Here’s an example code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class RealtimeFileReader {
public static void main(String[] args) {
String filePath = "path/to/file.txt";
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while (true) {
if ((line = br.readLine()) != null) {
// 处理每一行的内容
System.out.println(line);
} else {
// 当文件内容读取完毕,可以进行相应的处理
// 例如:休眠一定时间后再次读取文件内容
Thread.sleep(1000);
}
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
In the code above, BufferedReader is used to read each line of a file and print it out. After all the content in the file has been read, additional actions can be taken, such as pausing for a certain amount of time before reading the file content again.