我的文件确实存在时获取文件未找到异常

时间:2020-03-06 08:28:09

标签: java eclipse file file-io filenotfoundexception

我在eclipse中有一个Java项目,并且有一种从文件中读取信息的方法。当我对该方法进行JUnit测试时,即使该文件位于我的工作树中并且使用了正确的类路径声明,也无法找到该文件。

读取文件的方法:

public static ArrayList<Issue> readIssuesFromFile(String filename) {
    ArrayList<Issue> issues = new ArrayList<Issue>();

    try {
        Scanner sc = new Scanner(new FileInputStream(filename));
        String text = "";
        while(sc.hasNextLine()) {
            text+= sc.nextLine();
            text+= "\n";
        }
    } catch (Exception e) {
        throw new IllegalArgumentException(e.getMessage());
    }
}

JUnit测试:

public void testReadIssueFromFile() {
    String test = "test-files/valid_file.txt";
    try {
        ArrayList<Issue> issues = IssueReader.readIssuesFromFile(testFile);
        assertEquals(issues.get(0).getIssueId(), 0);
    } catch (Exception e) {
        fail(e.getMessage());
    }
}

工作树:

->Project
 ->src
  ->.java file containing method
 ->test
  ->JUnit test file
 ->test-files
  ->txt file

1 个答案:

答案 0 :(得分:0)

根据您的工作树,我认为您的路径应为:

../test-files/valid_file.txt

您使用的路径(test-files/valid_file.txt表示在JUnit文件的文件夹中搜索名为test-files的文件夹,并在此文件夹中搜索名为valid_file.txt的文件。

根据您的工作树情况并非如此。因此,您需要..移到上一级,在其中可以找到文件夹test-files

如果仍然无法正常运行,则可以尝试通过打印已使用的路径来调试程序:

try {
    /* Here you can replace the period with another path like "test-files/valid_file.txt" 
    * to see the absolute path of it
    */
    System.out.print(new java.io.File( "." ).getCanonicalPath());
} catch (IOException e) {
    e.printStackTrace();
}