gpt4 book ai didi

java - 使用 Files.walkFileTree 时如何忽略 AccessDeniedExceptions?

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

我想跟踪完整的硬盘分区(例如 D:),但出现以下异常:

AccessDeniedException  
java.nio.file.AccessDeniedException: D:System Volume Information
at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:83)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97)

如何忽略此异常并继续遍历文件树?

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;
}
});
}

/**
* 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);

// print out event
log.info("event.kind().name() {}: child {}", event.kind().name(), child);

// 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);
}
}

编辑这是完整的堆栈跟踪:

Apr 12, 2018 11:20:29 PM com.km.filewatcher.FileWatcher main
SEVERE: AccessDeniedException
java.nio.file.AccessDeniedException: D:System Volume Information
at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:83)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102)
at sun.nio.fs.WindowsDirectoryStream.<init>(WindowsDirectoryStream.java:86)
at sun.nio.fs.WindowsFileSystemProvider.newDirectoryStream(WindowsFileSystemProvider.java:518)
at java.nio.file.Files.newDirectoryStream(Files.java:457)
at java.nio.file.FileTreeWalker.visit(FileTreeWalker.java:300)
at java.nio.file.FileTreeWalker.next(FileTreeWalker.java:372)
at java.nio.file.Files.walkFileTree(Files.java:2706)
at java.nio.file.Files.walkFileTree(Files.java:2742)
at com.km.filewatcher.FileWatcher.walkAndRegisterDirectories(FileWatcher.java:68)
at com.km.filewatcher.FileWatcher.<init>(FileWatcher.java:51)
at com.km.filewatcher.FileWatcher.main(FileWatcher.java:140)

最佳答案

您可以实现visitFileFailed方法并返回 FileVisitResult.SKIP_SUBTREE 以在遇到 AccessDeniedException 时跳过该目录。

public FileVisitResult visitFileFailed(T file, IOException exc) throws IOException

Invoked for a file that could not be visited. Unless overridden, this method re-throws the I/O exception that prevented the file from being visited.

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);
}
});

请注意,如果不是 AccessDeniedException 类型,这仍然会引发异常。如果这不是您想要的行为,只需直接返回 SKIP_SUBTREE 即可。

关于java - 使用 Files.walkFileTree 时如何忽略 AccessDeniedExceptions?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49803363/

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