通过Java中的walkFileTree查找和读取USB目录中的所有文件时,拔出了USB,设备拔出时如何进行异常处理
时间: 2023-05-22 13:03:28 浏览: 47
在文件树遍历过程中,如果设备被拔出,Java中的walkFileTree会抛出FileSystemException异常。我们可以通过捕获该异常并在catch块中进行相关处理,比如输出错误信息或者直接终止遍历。一个简单的异常处理代码示例如下:
try {
Files.walkFileTree(usbPath, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
// 处理文件
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
// 处理目录
return FileVisitResult.CONTINUE;
}
});
} catch (FileSystemException e) {
// 设备拔出异常,进行相关处理
System.err.println("设备已拔出,请插入设备后重新运行程序!");
} catch (IOException e) {
// 其它IO异常,进行相关处理
e.printStackTrace();
}