java - 当我的文件确实存在时,出现文件未找到异常

标签 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

最佳答案

根据你的工作树,我认为你的路径应该是:

../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();
}

关于java - 当我的文件确实存在时,出现文件未找到异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60560162/

相关文章:

c++ - 为什么我的 fwrite 命令只运行一次?

c++ - 在 C++ (windows) 中监控文件变化

java - App Engine 中的整数类型存储

java - 如何在intellij中查找.properties资源(i18n)键的代码用法

java - 将多个 String 和 ImageView 添加到一个 View

eclipse - 在eclipse中集成Redmine和Mylyn生成查询失败

java - 如何跳过包含字符串的 .last Modified() 文件,并选择下一个 .last Modified() 文件

java - Webstart 应用程序的所有 jar 都需要权限属性吗?

android - 尝试从 v 18.x 更新 Eclipse ADT - v 20.0.0 或更高版本

java - WSO2 Eclipse Luna 数据映射器加载错误