即使文件存在,FileNotFoundException也是如此

Arn*_*tta 1 java filenotfoundexception java.util.scanner

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

}
Run Code Online (Sandbox Code Playgroud)

以上是我的代码(我也有一个错误的图像:http: //folk.uio.no/arnabkd/test/images/error-code-task.jpg

如您所见,txt文件与StormAnalysis.java文件位于同一文件夹中.此外,如果我将文件路径更改为"weather.dat"(作为另一个任务/问题),代码也可以工作.

任何想法将不胜感激!

小智 8

该文件不存在.如果它不会抛出异常:-)

可能的罪魁祸首是工作目录与预期的不同(即,当前工作目录不包含具有该名称的文件).这可以通过使用文件的绝对路径并观察它是否正确加载来轻松验证.

或者,要查找当前目录:

String cwd = new File(".").getAbsolutePath();
Run Code Online (Sandbox Code Playgroud)

快乐的编码.