我在依賴inotify事件的JDK7中使用Watcher。如果該文件位於NFS上,我希望我的程序回退並使用輪詢。有沒有辦法檢測文件是否在遠程驅動器上(除了使用Runtime.exec和解析裝載表)?我現在只關心Linux兼容性。在Java中檢測遠程文件
我想一個選擇是在程序啓動時使用inotify和polling,但如果創建了我的文件的inotify事件,則禁用輪詢線程。
我在依賴inotify事件的JDK7中使用Watcher。如果該文件位於NFS上,我希望我的程序回退並使用輪詢。有沒有辦法檢測文件是否在遠程驅動器上(除了使用Runtime.exec和解析裝載表)?我現在只關心Linux兼容性。在Java中檢測遠程文件
我想一個選擇是在程序啓動時使用inotify和polling,但如果創建了我的文件的inotify事件,則禁用輪詢線程。
您應該可以通過FileStore.type()獲得關於底層文件系統類型的相對可靠的信息。
它肯定會告訴你,如果它是一個NFS或CIFS,不確定其他網絡安裝類型。
但是我沒有關於它有多可靠的信息,@ hoaz建議檢查事件是否經過可能是一個好主意。
我有同樣的問題。我已經通過在de main類中創建一個新線程並定期觸摸這些文件來解決這個問題,從而引發了一個新的更改事件。
該示例每10秒輪詢一次目錄會觸摸一下。
這裏的代碼示例:
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這應該是答案 –