假设我有一个类和一个方法
class A {
void foo() throws Exception() {
...
}
}
Run Code Online (Sandbox Code Playgroud)
现在我想为A一个流传递的每个实例调用foo,如:
void bar() throws Exception {
Stream<A> as = ...
as.forEach(a -> a.foo());
}
Run Code Online (Sandbox Code Playgroud)
问题:如何正确处理异常?代码无法在我的机器上编译,因为我没有处理foo()可能抛出的异常.在throws Exception的bar似乎是没用在这里.这是为什么?
我正在尝试计算光盘上文件的大小.在java-7中,这可以使用Files.walkFileTree来完成,如我在这里的回答所示.
但是,如果我想使用java-8流来执行此操作,它将适用于某些文件夹,但不适用于所有文件夹.
public static void main(String[] args) throws IOException {
long size = Files.walk(Paths.get("c:/")).mapToLong(MyMain::count).sum();
System.out.println("size=" + size);
}
static long count(Path path) {
try {
return Files.size(path);
} catch (IOException | UncheckedIOException e) {
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码适用于路径,a:/files/但c:/它会抛出异常
Exception in thread "main" java.io.UncheckedIOException: java.nio.file.AccessDeniedException: c:\$Recycle.Bin\S-1-5-20
at java.nio.file.FileTreeIterator.fetchNextIfNeeded(Unknown Source)
at java.nio.file.FileTreeIterator.hasNext(Unknown Source)
at java.util.Iterator.forEachRemaining(Unknown Source)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Unknown Source)
at java.util.stream.AbstractPipeline.copyInto(Unknown Source)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(Unknown Source)
at java.util.stream.AbstractPipeline.evaluate(Unknown Source)
at java.util.stream.LongPipeline.reduce(Unknown …Run Code Online (Sandbox Code Playgroud) 以下是一些简单的代码来测试该Files.walkFileTree()方法.但是,/etc/ssl/private具有这些权限(rwx--x---)的文件夹会引发异常,即使我认为我使用if语句(if (permissions.equals("rwx--x---"))保护它也是如此.
我究竟做错了什么?提前致谢.
public static void main (String []args) throws IOException, InterruptedException
{
Files.walkFileTree(Paths.get("/"), new WalkingTheThing2());
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException
{
PosixFileAttributeView posixView = Files.getFileAttributeView(dir, PosixFileAttributeView.class);
PosixFileAttributes posixAttr = posixView.readAttributes();
String permissions =PosixFilePermissions.toString(posixAttr.permissions());
if (permissions.equals("rwx--x---"))
{
return FileVisitResult.SKIP_SUBTREE;
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
try{
System.out.println(file.getFileName()+" " +Files.size(file));
return FileVisitResult.CONTINUE;
}
catch(IOException io){return FileVisitResult.CONTINUE;}
}
Run Code Online (Sandbox Code Playgroud)
我得到的例外是: java.nio.file.AccessDeniedException: /etc/ssl/private …
我想跟踪完整的硬盘分区(例如 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)
Run Code Online (Sandbox Code Playgroud)
如何忽略此异常并继续遍历文件树?
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
{ …Run Code Online (Sandbox Code Playgroud) 编辑:这似乎不可能,请参阅https://bugs.openjdk.java.net/browse/JDK-8039910。
我有一个帮助类,它提供了一个Stream<Path>. 这段代码只是Files.walk对输出进行包装和排序:
public Stream<Path> getPaths(Path path) {
return Files.walk(path, FOLLOW_LINKS).sorted();
}
Run Code Online (Sandbox Code Playgroud)
由于遵循符号链接,如果文件系统中出现循环(例如 符号链接x -> .),则 中使用的代码Files.walk会抛出UncheckedIOException包装 的实例FileSystemLoopException。
在我的代码中,我想捕获此类异常,例如,只记录一条有用的消息。一旦发生这种情况,结果流可以/应该停止提供条目。
我尝试将.map(this::catchException)和添加.peek(this::catchException)到我的代码中,但在此阶段未捕获异常。
Path checkException(Path path) {
try {
logger.info("path.toString() {}", path.toString());
return path;
} catch (UncheckedIOException exception) {
logger.error("YEAH");
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
如果有的话,我如何UncheckedIOException在我的代码中捕获 an发出 a Stream<Path>,以便路径的使用者不会遇到此异常?
例如,以下代码永远不会遇到异常:
List<Path> paths = getPaths().collect(toList());
Run Code Online (Sandbox Code Playgroud)
现在,异常是由代码调用触发的collect(我可以在那里捕获异常):
java.io.UncheckedIOException: java.nio.file.FileSystemLoopException: /tmp/junit5844257414812733938/selfloop
at java.nio.file.FileTreeIterator.fetchNextIfNeeded(FileTreeIterator.java:88)
at …Run Code Online (Sandbox Code Playgroud) java ×6
java-stream ×3
nio ×3
io ×2
java-8 ×2
directory ×1
exception ×1
file ×1
file-access ×1