Java 当I文件确实存在时,获取未找到文件异常

Java 当I文件确实存在时,获取未找到文件异常,java,eclipse,file,file-io,filenotfoundexception,Java,Eclipse,File,File Io,Filenotfoundexception,我在eclipse中有一个java项目,并且有一个从文件中读取信息的方法。当我对该方法进行JUnit测试时,它无法找到该文件,即使它在我的工作树中,并且我使用了正确的类路径声明 读取文件的方法: public static ArrayList<Issue> readIssuesFromFile(String filename) { ArrayList<Issue> issues = new ArrayList<Issue>(); try {

我在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());
    }
}

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

../test-files/valid_file.txt
您使用的路径(
test files/valid_file.txt
)意味着在JUnit文件的文件夹中搜索名为
test files
的文件夹,并在此文件夹中搜索名为
valid_file.txt
的文件


根据你的工作树,情况并非如此。因此,您需要
移动到上面的级别,在那里您可以找到文件夹
测试文件

如果仍然不起作用,可以尝试通过如下方式打印您使用的路径来调试您的程序:

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

您可能希望开始使用构建工具(如maven)并遵循建议的目录布局。然后,您的txt文件将被放置在test/resources中,并可以作为资源读取。文件的根目录取决于您的环境,因此存在风险。不完全如此。我是一名学生,在我们过去做过的类似项目中,我不需要使用构建工具进行布局,因为学校喜欢特定的布局。当我尝试此方法时,系统无法找到path@John我已经用调试方法更新了我的答案
../test-files/valid_file.txt
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();
}