FileNotFoundException even when the file is there

[亡魂溺海] 提交于 2019-11-30 09:47:51

问题


public StormAnalysis(){
    try {       
        fScanner = new Scanner(new File("tracks1949to2010_epa.txt"));
        while(fScanner.hasNextLine()){
            System.out.println(fScanner.nextLine());
        }
    } catch (FileNotFoundException e) {
        System.out.println("File not found. Try placing the tracks1949to2010_epa.txt in the same folder as StormAnalysis.java");    
        e.printStackTrace();
    }

}

The above is my code (and I also have an image of the error : http://folk.uio.no/arnabkd/test/images/error-code-task.jpg

As you can see, the txt file is in the same folder as the StormAnalysis.java file. In addition, the code works if I change the file path to "weather.dat" (which was given as another task/problem).

Any ideas will be appreciated!


回答1:


The file isn't there. If it was it wouldn't throw the exception :-)

The likely culprit is the working directory differs from what is expected (that is, the current working directory does not contain a file with that name). This can be trivially verified with using the file's absolute path and observing that it is loaded correctly.

Alternatively, to find the current directory:

String cwd = new File(".").getAbsolutePath();

Happy coding.




回答2:


Eclipse copies (only) the class files into a bin\classes directory by default (unless this has been changed to another directory), before running a Java application. For all practical purposes, this directory is different from the src directory where the input file is present. You will have to configure the project's build properties in Eclipse to copy the input file (or all files of type .txt) to the output directory as well. This will make the file available in the same directory where the class file is, enabling the file to be read.




回答3:


The Eclipse cwd is the Project folder, one level above bin and src.

Directory of ...eclipse-workspace\File IO
05/30/2018  07:52 PM    <DIR>          bin
05/30/2018  07:48 PM               148 sample.txt
05/30/2018  07:46 PM    <DIR>          src

testFile = new File("Sample.txt");
System.out.println(testFile.getAbsolutePath());


来源:https://stackoverflow.com/questions/6197187/filenotfoundexception-even-when-the-file-is-there

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!