使用FileSystems API。以下是一个示例代码:
import java.nio.file.*;
import java.util.*;
public class FolderWatcher {
private final WatchService watchService;
private final Map watchKeyPathMap;
public FolderWatcher(Path folderPath) throws Exception {
this.watchService = FileSystems.getDefault().newWatchService();
this.watchKeyPathMap = new HashMap<>();
registerFolder(folderPath);
}
private void registerFolder(Path folderPath) throws Exception {
WatchKey watchKey = folderPath.register(
watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_DELETE);
watchKeyPathMap.put(watchKey, folderPath);
}
public void startWatching() throws Exception {
WatchKey watchKey;
while ((watchKey = watchService.take()) != null) {
for (WatchEvent watchEvent : watchKey.pollEvents()) {
WatchEvent.Kind watchEventKind = watchEvent.kind();
if (watchEventKind == StandardWatchEventKinds.OVERFLOW) {
continue;
}
WatchEvent pathWatchEvent = (WatchEvent) watchEvent;
Path fileName = pathWatchEvent.context();
Path folderPath = watchKeyPathMap.get(watchKey);
Path absolutePath = folderPath.resolve(fileName);
// Do something with the file
}
if (!watchKey.reset()) {
watchKeyPathMap.remove(watchKey);
if (watchKeyPathMap.isEmpty()) {
break;
}
}
}
}
}
在您的代码中,您可以使用以上示例代码来监听文件夹以进行文件更改,并根据需要进行修改。