같은 문제가있었습니다. 주 클래스에서 새 스레드를 만들고 파일을 주기적으로 만져서 새로운 변경 이벤트가 시작되면이를 해결했습니다.
샘플은 10 초마다 dir을 폴링합니다. 여기
코드 샘플 :
package com.ardevco.files;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileTime;
import java.util.ArrayList;
import java.util.List;
public class Touch implements Runnable {
private Path touchPath;
public Touch(Path touchPath) {
this.touchPath = touchPath;
this.checkPath = checkPath;
}
public static void touch(Path file) throws IOException {
long timestamp = System.currentTimeMillis();
touch(file, timestamp);
}
public static void touch(Path file, long timestamp) throws IOException {
if (Files.exists(file)) {
FileTime ft = FileTime.fromMillis(timestamp);
Files.setLastModifiedTime(file, ft);
}
}
List<Path> listFiles(Path path) throws IOException {
final List<Path> files = new ArrayList<>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) {
for (Path entry : stream) {
if (Files.isDirectory(entry)) {
files.addAll(listFiles(entry));
}
files.add(entry);
}
}
return files;
}
@Override
public void run() {
while (true) {
try {
for (Path path : listFiles(touchPath)) {
touch(path);
}
} catch (IOException e) {
System.out.println("Exception: " + e);
}
try {
Thread.sleep(10000L);
} catch (InterruptedException e) {
System.out.println("Exception: " + e);
}
}
}
}
당신은 inotify를 시도하고 프로그램 파일을 업데이트 할 수 있습니다. 당신이 이벤트를받는다면, 그렇지 않다면, 폴링으로 전환하십시오. – hoaz
java.nio.file.WatchService 문서는 특별한 경우에 사용할 더 나은 메커니즘이 없다면 시계 서비스 구현이 폴링으로 대체된다는 것을 의미합니다. NFS 파일 시스템에서도 사용할 수 있으며 폴링을 직접 구현할 필요가 없습니다. –
@OlegEstekhin이 답변을해야합니다. –