[英]java.io.FileNotFoundException (File not found) using Scanner. What's wrong in my code?
我的 netbeans“/build/classes”目录中有一个 .txt 文件(“file.txt”)。
在同一目录中有为以下代码编译的 .class 文件:
try {
File f = new File("file.txt");
Scanner sc = new Scanner(f);
}
catch (IOException e) {
System.out.println(e);
}
调试代码(“Scanner sc ..”中的断点)启动异常并打印以下内容:
java.io.FileNotFoundException: file.txt(系统找不到指定的文件)
我也尝试使用“/file.txt”和“//file.txt”,但结果相同。
预先感谢您的任何提示
如果您只使用new File("pathtofile")
该路径是相对于您当前的工作目录的,而该目录根本不一定是您的类文件所在的位置。
如果您确定该文件位于类路径中的某个位置,则可以改用以下模式:
URL path = ClassLoader.getSystemResource("file.txt");
if(path==null) {
//The file was not found, insert error handling here
}
File f = new File(path.toURI());
JVM 将在当前工作目录中查找该文件。
这取决于您的 IDE 设置(您的程序如何执行)。
为了弄清楚它预计file.txt
被定位,你可以这样做
System.out.println(new File("."));
如果它例如输出
/some/path/project/build
您应该将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.