Java中可以使用java.nio.file包中的WatchService类来监听文件的变化,并使用BufferedReader类来读取文件。
下面是一个简单的示例代码:
import java.io.BufferedReader;import java.io.IOException;import java.nio.file.*;public class FileWatcherExample {public static void main(String[] args) throws IOException, InterruptedException {// 创建WatchService对象WatchService watchService = FileSystems.getDefault().newWatchService();// 注册监听的文件夹Path directory = Paths.get("path/to/directory");directory.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);// 循环监听文件变化while (true) {WatchKey key;try {// 获取下一个文件变化的事件key = watchService.take();} catch (InterruptedException e) {return;}// 处理文件变化的事件for (WatchEvent<?> event : key.pollEvents()) {WatchEvent.Kind<?> kind = event.kind();// 过滤掉非修改事件if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {@SuppressWarnings("unchecked")WatchEvent<Path> pathEvent = (WatchEvent<Path>) event;Path modifiedFile = pathEvent.context();// 读取文件内容try (BufferedReader reader = Files.newBufferedReader(directory.resolve(modifiedFile))) {String line;while ((line = reader.readLine()) != null) {// 处理文件内容System.out.println(line);}} catch (IOException e) {e.printStackTrace();}}}// 重置WatchKey以接收更多的文件变化事件boolean valid = key.reset();if (!valid) {break;}}}}在上述代码中,我们使用WatchService来创建一个文件监视器,并使用register()方法注册要监听的文件夹和事件类型。接下来,我们使用一个无限循环来等待文件变化事件的发生。在循环中,我们使用take()方法来获取下一个文件变化事件的WatchKey对象,然后遍历该WatchKey对象的所有事件。在事件处理循环中,我们过滤掉非修改事件,并使用Files.newBufferedReader()方法来创建一个BufferedReader对象,从而读取修改后的文件内容。
请注意,需要将"path/to/directory"替换为要监听的实际文件夹的路径。此外,上述代码只演示了读取文件内容的部分,您需要根据实际需求进行相应的处理。