使用 Scanner 的 java.io.FileNotFoundException(未找到文件)。我的代码有什么问题?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10830460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java.io.FileNotFoundException (File not found) using Scanner. What's wrong in my code?
提问by dragonmnl
I've a .txt file ("file.txt") in my netbeans "/build/classes" directory.
我的 netbeans“/build/classes”目录中有一个 .txt 文件(“file.txt”)。
In the samedirectory 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
预先感谢您的任何提示
回答by Joel Westberg
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());
回答by aioobe
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 whereit 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
在构建目录中(或指定相对于构建目录的正确路径)。
回答by Eng.Fouad
Try:
尝试:
File f = new File("./build/classes/file.txt");
回答by Kumar Vivek Mitra
Use "." to denote the current directory
String path = "./build/classes/file.txt";
File f = new File(path);