如何对这样的 watchservice 进行单元测试:
/**
* Function to look for changes in a determinate directory
* @param directory is the directory where to look for the changes
* @return return a boolean that is true if have changes or false if not
*/
private static boolean watchDirectory(final String directory){
boolean flag = false;
Path path = Paths.get(directory);
try {
// get watch service which will monitor the directory
WatchService watcher = path.getFileSystem().newWatchService();
// associate watch service with the directory to listen to the event types
path.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);
System.out.println("\nMonitoring directory for changes...");
// listen to events
WatchKey watchKey = watcher.take();
// get list of events as they occur
List<WatchEvent<?>> events = watchKey.pollEvents();
for (WatchEvent event : events) {
flag = false;
//check if the events refers to a new file created
if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
flag = true;
System.out.println("Created: " + event.context().toString() + " ;");
}
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return flag;
}
它正在查找目录中的更改,如果创建了新文件,它返回一个值为 true 的标志,如果我没有找到更改,则返回该标志为 false。
饮歌长啸
相关分类