FileNotFoundException的方法

时间:2013-04-28 19:14:46

标签: java filenotfoundexception

以下不断报告相同的错误。

public static ArrayList<File> findMatches(File directory, String pattern) throws FileNotFoundException {
60         ArrayList<File> container = new ArrayList<File>();
61 
62         return container;
63     }

我按以下方式初始化

ArrayList<File> matched = findMatches(new File("hw9"), "FileFinder.java");

错误:      错误:未报告的异常FileNotFoundException;必须被抓住或宣布被抛出

任何解决方案?

修改

终于找到了如何做到这一点!

public static ArrayList<File> findMatches(File directory, String pattern) throws FileNotFoundException {
    ArrayList<File> container = new ArrayList<File>();

    try {
        if (!directory.exists() && !directory.canRead() && !directory.isDirectory()) {
            throw new FileNotFoundException();
        }
        File[] fileStack = directory.listFiles();
        for (int i = 0; i < fileStack.length; i++) {
            if (patternMatches(pattern, fileStack[i].getName())) {
                container.add(fileStack[i]);
            }
        }
    } catch (NullPointerException e) {
        throw new FileNotFoundException();
    }
    return container;
}

1 个答案:

答案 0 :(得分:5)

  

任何解决方案?

嗯,你有三个选择:

  • 更改findMatches,以便它不会声明它会抛出FileNotFoundException(此时肯定不会抛出它)
  • 在呼叫代码中抓住FileNotFoundException
  • 声明调用findMatches的方法抛出FileNotFoundException

我们无法从您提供的极少量信息中找出最合适的信息。

您还需要阅读Exceptions part of the Java tutorial或任何优秀Java书籍/教程的异常报道。了解为什么您收到此错误以及为何上述更改会解决此问题非常重要。

相关问题