在java中,当我添加,更改或删除任何文件时,我希望程序在另一个目录中执行相同的操作。这意味着,如果我添加一个文件“test.txt”在E:// aaa中,程序应该从E:// aaa复制“test.txt”到D:// bbb。如何在WatchService中获得真正的路径
我使用java.nio.file.WatchService
来实现它,但我无法获取文件的真实路径程序,这是我的代码:
public void watchPath(Path watchPath, Path targetPath) throws IOException, InterruptedException {
try (WatchService watchService = FileSystems.getDefault().newWatchService()) {
watchPath.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_DELETE);
while (true) {
final WatchKey key = watchService.take();
for (WatchEvent<?> watchEvent : key.pollEvents()) {
final Kind<?> kind = watchEvent.kind();
if (kind == StandardWatchEventKinds.OVERFLOW) {
continue;
}
final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
Path systemFileDir = (Path) key.watchable(); // TODO Here can not get the real path
//System.out.println(systemFileDir.toString()); // E:/aaa
//System.out.println(systemFileDir.toAbsolutePath()); // E:/aaa
//System.out.println(systemFileDir.toRealPath()); // E:/aaa
final Path path = watchEventPath.context();
String fileAbsPath = systemFileDir + File.separator + path;
Path original = Paths.get(fileAbsPath);
String targetAbsPath = fileAbsPath.replace(watchPath.toString(), targetPath.toString());
Path target = Paths.get(targetAbsPath);
File file = new File(targetAbsPath);
if (kind == StandardWatchEventKinds.ENTRY_CREATE || kind == StandardWatchEventKinds.ENTRY_MODIFY) {
if (file.isDirectory() && !file.exists()) { // 如果是目录
file.mkdirs();
} else {
Files.copy(original, target, StandardCopyOption.REPLACE_EXISTING);
}
}
if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
Files.delete(target);
}
}
boolean valid = key.reset();
if (!valid) {
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
现在的问题是,当我在E添加一个文件或目录:// AAA/X,程序不能得到真正的路径。例如,我添加了文件E://aaa/x/test.txt,我希望我能得到这个绝对路径,然后将它复制到目的地,但我只是得到RootPath E:// aaa。
如何我可以解决它吗?谢谢!
如果我添加E:\\ aaa \ x中的一个文件夹,我想要得到路径“E:\\ aaa \ x \ y”,但是'systemFileDir.resolve(watchE ventPath.context())'刚刚返回“E:\\ aaa \ x”,我不知道如何让我的新文件夹名称为“y”。 – Leon
@JasonGan查看我的编辑。但实质上:http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/essential/io/examples/WatchDir.java – sorifiend