gpt4 book ai didi

java - 如何在java中的FileWacther中查看多个硬盘分区

转载 作者:行者123 更新时间:2023-12-02 02:12:20 32 4
gpt4 key购买 nike

我正在使用 FileWatcher 来观察整个硬盘分区,在我的情况下是 D 驱动器,例如:D:/代码在我提供的一个路径下工作正常,我想要的就是观察其他硬盘分区,就像 C 一样:,D: 和 E: 我怎样才能做到这一点,这是代码

public class FileWatcher {
private final WatchService watcher;
private final Map<WatchKey, Path> keys;
static Logger log = LoggerFactory.getLogger(GitCloneRepo.class);

/**
* Creates a WatchService and registers the given directory
*/
FileWatcher(Path dir) throws IOException {
this.watcher = FileSystems.getDefault().newWatchService();
this.keys = new HashMap<WatchKey, Path>();

walkAndRegisterDirectories(dir);
}

/**
* Register the given directory with the WatchService; This function will be called by FileVisitor
*/
private void registerDirectory(Path dir) throws IOException
{
WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
keys.put(key, dir);
}

/**
* Register the given directory, and all its sub-directories, with the WatchService.
*/
private void walkAndRegisterDirectories(final Path start) throws IOException {
// register directory and sub-directories
Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
registerDirectory(dir);
return FileVisitResult.CONTINUE;
}

@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
if (exc instanceof AccessDeniedException) {
return FileVisitResult.SKIP_SUBTREE;
}

return super.visitFileFailed(file, exc);
}
});
}

/**
* Process all events for keys queued to the watcher
*/
void processEvents() {
for (;;) {

// wait for key to be signalled
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException x) {
log.error("InterruptedException ",x);
return;
}

Path dir = keys.get(key);
if (dir == null) {
log.warn("WatchKey not recognized!!");
continue;
}

for (WatchEvent<?> event : key.pollEvents()) {
@SuppressWarnings("rawtypes")
WatchEvent.Kind kind = event.kind();

// Context for directory entry event is the file name of entry
@SuppressWarnings("unchecked")
Path name = ((WatchEvent<Path>)event).context();
Path child = dir.resolve(name);
log.info("watching files");
// print out event
if (kind == ENTRY_MODIFY) {
log.info("event.kind().name() {}: child {}", event.kind().name(), child);
log.info("child {} ends with docx? {} ",child,child.endsWith(".docx"));
String c= child.toString();
log.info("**child {}***c.endsWith(.docx)"
+ ""
+ " {}",c,c.endsWith(".docx"));
}
// if directory is created, and watching recursively, then register it and its sub-directories
if (kind == ENTRY_CREATE) {
try {
if (Files.isDirectory(child)) {
walkAndRegisterDirectories(child);
}
} catch (IOException x) {
// do something useful
}
}
}

// reset key and remove from set if directory no longer accessible
boolean valid = key.reset();
if (!valid) {
keys.remove(key);

// all directories are inaccessible
if (keys.isEmpty()) {
break;
}
}
}
}


//working code
public static void main(String[] args) throws IOException {
try{
Path dir = Paths.get("D:");
FileWatcher fileWatcher=new FileWatcher(dir);
fileWatcher.processEvents();
}

catch (AccessDeniedException xx) {
log.error("AccessDeniedException ",xx);
}
catch (FileSystemException x) {
log.error("exception",x);
}
}

}

我看了这个问题,但似乎没有解决我的问题 How to implement file watcher to Watch multiple directories

最佳答案

您的 processEvents 方法进入无限循环,直到线程中断或路径消失才返回,这意味着 processEvents 之后的任何代码都不会返回执行直到完成。如果您希望 main 方法启动多个观察程序,则需要从其他线程调用 processEvents,例如使用 Java 8:

// Create watchers
List<FileWatcher> watchers = new ArrayList<>();
try{
watchers.add(new FileWatcher(Paths.get("D:")));
watchers.add(new FileWatcher(Paths.get("E:")));
} catch (AccessDeniedException xx) {
log.error("AccessDeniedException ",xx);
} catch (FileSystemException x) {
log.error("exception",x);
}

// Create and start threads
List<Thread> threads = watchers.stream()
.map(w -> new Thread(w::processEvents))
.peek(Thread::start)
.collect(Collectors.toList());

使用 Java 7:

// Create watchers
List<FileWatcher> watchers = new ArrayList<>();
try{
watchers.add(new FileWatcher(Paths.get("D:")));
watchers.add(new FileWatcher(Paths.get("E:")));
} catch (AccessDeniedException xx) {
log.error("AccessDeniedException ",xx);
} catch (FileSystemException x) {
log.error("exception",x);
}

// Create and start threads
List<Thread> threads = new ArrayList<>();
for (FileWatcher watcher : watchers) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
watcher.processEvents();
}
});
thread.start();
threads.add(thread);
}

关于java - 如何在java中的FileWacther中查看多个硬盘分区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49821392/

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