简体   繁体   English

FileNotFoundException 即使文件在那里

[英]FileNotFoundException even when the file is there

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以上是我的代码(我也有错误的图像: 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.如您所见,txt 文件与 StormAnalysis.java 文件位于同一文件夹中。 In addition, the code works if I change the file path to "weather.dat" (which was given as another task/problem).此外,如果我将文件路径更改为“weather.dat”(作为另一个任务/问题给出),该代码将起作用。

Any ideas will be appreciated!任何想法将不胜感激!

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.快乐编码。

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.在运行 Java 应用程序之前,Eclipse 默认情况下(仅)将 class 文件复制到bin\classes目录中(除非已将其更改为另一个目录)。 For all practical purposes, this directory is different from the src directory where the input file is present.出于所有实际目的,此目录与输入文件所在的src目录不同。 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.您还必须在 Eclipse 中配置项目的构建属性,以将输入文件(或 type.txt 的所有文件)复制到 output 目录。 This will make the file available in the same directory where the class file is, enabling the file to be read.这将使该文件在 class 文件所在的同一目录中可用,从而可以读取该文件。

The Eclipse cwd is the Project folder, one level above bin and src. Eclipse cwd 是 Project 文件夹,在 bin 和 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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM