In java, when I add or change or delete any file, I hope the program execute the same action in another directory.It means, if I add a file "test.txt" in E://aaa, the program should copy "test.txt" from E://aaa to D://bbb。
I use java.nio.file.WatchService
to implement it, but I can not get files' real path in program, Here is my code:
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();
}
}
Now the question is, when I add a file or directory in E://aaa/x, the program can not get the real path. For example, I added the file E://aaa/x/test.txt, I hope I can get this absolute path then copy it to destination, but I just get the RootPath E://aaa。
How Can I solve it ? Thx!