gpt4 book ai didi

java - 单元测试 WatchService

转载 作者:行者123 更新时间:2023-11-30 02:01:50 25 4
gpt4 key购买 nike

如何对这样的 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。

最佳答案

关于java - 单元测试 WatchService,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52588728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com