简体   繁体   English

使用 Scanner 的 java.io.FileNotFoundException(未找到文件)。 我的代码有什么问题?

[英]java.io.FileNotFoundException (File not found) using Scanner. What's wrong in my code?

I've a .txt file ("file.txt") in my netbeans "/build/classes" directory.我的 netbeans“/build/classes”目录中有一个 .txt 文件(“file.txt”)。

In the same directory there is the .class file compiled for the following code:同一目录中有为以下代码编译的 .class 文件:

try {
File f = new File("file.txt");
Scanner sc = new Scanner(f);
}
catch (IOException e) {
   System.out.println(e);
}

Debugging the code (breakpoint in "Scanner sc ..") an exception is launched and the following is printed:调试代码(“Scanner sc ..”中的断点)启动异常并打印以下内容:

java.io.FileNotFoundException: file.txt (the system can't find the specified file) java.io.FileNotFoundException: file.txt(系统找不到指定的文件)

I also tried using "/file.txt" and "//file.txt" but same result.我也尝试使用“/file.txt”和“//file.txt”,但结果相同。

Thank you in advance for any hint预先感谢您的任何提示

If you just use new File("pathtofile") that path is relative to your current working directory, which is not at all necessarily where your class files are.如果您只使用new File("pathtofile")该路径是相对于您当前的工作目录的,而该目录根本不一定是您的类文件所在的位置。

If you are sure that the file is somewhere on your classpath, you could use the following pattern instead:如果您确定该文件位于类路径中的某个位置,则可以改用以下模式:

URL path = ClassLoader.getSystemResource("file.txt");
if(path==null) {
     //The file was not found, insert error handling here
}
File f = new File(path.toURI());

The JVM will look for the file in the current working directory. JVM 将在当前工作目录中查找该文件。

Where this is depends on your IDE settings (how your program is executed).这取决于您的 IDE 设置(您的程序如何执行)。

To figure out where it expects file.txt to be located, you could do为了弄清楚预计file.txt被定位,你可以这样做

System.out.println(new File("."));

If it for instance outputs如果它例如输出

/some/path/project/build

you should place file.txt in the build directory (or specify the proper path relative to the build directory).您应该将file.txt放在构建目录中(或指定相对于构建目录的正确路径)。

尝试:

File f = new File("./build/classes/file.txt");
Use "." to denote the current directory

String path = "./build/classes/file.txt";

File f = new File(path);

文件对象加载,在其当前目录中寻找匹配项....直接在您的项目文件夹中,您的类文件不是在您的源文件中加载的.....将文件直接放在项目文件夹中

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

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