Java 编译器抱怨未报告的 IOException

Java compiler complaining about unreported IOException

我正在尝试编写一种列出目录中所有非隐藏文件的方法。但是,当我添加条件 !Files.isHidden(filePath) 时,我的代码无法编译,并且编译器 returns 出现以下错误:

java.lang.RuntimeException: Uncompilable source code - unreported exception 
java.io.IOException; must be caught or declared to be thrown

我试图捕捉 IOException,但编译器仍然拒绝编译我的代码。有什么明显的我想念的东西吗?代码如下。

try {    
    Files.walk(Paths.get(root)).forEach(filePath -> {
        if (Files.isRegularFile(filePath) && !Files.isHidden(filePath)) {
            System.out.println(filePath);            
        } });
} catch(IOException ex) {    
  ex.printStackTrace(); 
} catch(Exception ex) {   
  ex.printStackTrace(); 
}

传递给Iterable#forEach的lambda表达式不允许抛出异常,所以你需要在那里处理它:

Files.walk(Paths.get(root)).forEach(filePath -> {
    try {
        if (Files.isRegularFile(filePath) && !Files.isHidden(filePath)) {
            System.out.println(filePath);
        }
    } catch (IOException e) {
        e.printStackTrace(); // Or something more intelligent
    }
});

isHiddenFile() 抛出 IOException,而您没有捕捉到它。实际上,forEach() 将 Consumer 作为参数,而 Consumer.accept() 不能抛出任何已检查的异常。因此,您需要通过传递给 forEach():

的 lambda 表达式来捕获异常 inside
Files.walk(Paths.get(root)).forEach(filePath -> {
    try {
        if (Files.isRegularFile(filePath) && !Files.isHidden(filePath)) {
            System.out.println(filePath);            
        } 
    }
    catch (IOException e) {
         // do something here
    }
});