为什么 WatchService 会生成如此多的操作?
2022-09-01 21:27:24
import java.io.*;
import java.nio.file.*;
public class Tmp {
public static void main(String [] args) throws IOException {
int count = 0;
Path path = Paths.get("C:\\tmp\\");
WatchService ws = null;
try {
ws = FileSystems.getDefault().newWatchService();
path.register(ws, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.OVERFLOW);
} catch (IOException ioe) {
ioe.printStackTrace();
}
while(true) {
WatchKey key = null;
try {
key = ws.take();
} catch(InterruptedException ie) {
ie.printStackTrace();
}
for(WatchEvent<?> event: key.pollEvents()) {
switch(event.kind().name()) {
case "OVERFLOW":
System.out.println(++count + ": OVERFLOW");
break;
case "ENTRY_MODIFY":
System.out.println(++count + ": File " + event.context() + " is changed!");
break;
case "ENTRY_CREATE":
System.out.println(++count + ": File " + event.context() + " is created!");
break;
case "ENTRY_DELETE":
System.out.println(++count + ": File " + event.context() + " is deleted!");
break;
default:
System.out.println(++count + ": UNKNOWN EVENT!");
}
}
key.reset();
}
}
}
当我运行这个,然后打开Notepad ++,然后创建一个新的空文件并将其保存在目录中时,我得到了输出:a.txt
C:\tmp\
1: File a.txt is created!
2: File a.txt is deleted!
3: File a.txt is created!
为什么?看起来该文件已创建,然后被删除,然后再次创建。为什么?
当我在文件中放置一些文本并保存它时,输出是:
4: File a.txt is changed!
5: File a.txt is changed!
为什么它改变了两次?