java 读取文件错误:找不到文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3835095/
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
Reading file error: File Not Found
提问by Bob
I have the follwing
我有以下
Scanner scanner = new Scanner(new File("hello.txt"));
while(scanner.hasNextInt()){
int i = scanner.nextInt();
System.out.println(i);
}
Why do I get an error when I run it? It says file not found (The system cannot find the files specificed)in java.io.fileinputstream. But the file does exist.
为什么我运行的时候会报错?它说file not found (The system cannot find the files specificed)在java.io.fileinputstream。但该文件确实存在。
回答by BalusC
You need to specify an absolutepath. Right now you're specifying a relativepath. The path is relative to the current working directory over which you have no control from inside the Java code. The relative path depends on how you're executing the Java code. In command prompt, it's the currently opened folder. In an IDE like Eclipse, it's the project's root folder. In a webapplication, it's the Server's binary folder, etc.
您需要指定绝对路径。现在您正在指定一个相对路径。该路径相对于当前工作目录,您无法从 Java 代码内部对其进行控制。相对路径取决于您执行 Java 代码的方式。在命令提示符下,它是当前打开的文件夹。在 Eclipse 等 IDE 中,它是项目的根文件夹。在 web 应用程序中,它是服务器的二进制文件夹等。
Scanner scanner = new Scanner(new File("/full/path/to/hello.txt"));
In a Windows environment, the above example equals to C:\full\path\to\hello.txt.
在 Windows 环境中,上面的示例等于C:\full\path\to\hello.txt.
If your actualintent is to place this file in the same folder of the currently running class, then you should be obtaining it as a classpath resource:
如果您的实际意图是将此文件放在当前正在运行的类的同一文件夹中,那么您应该将其作为类路径资源获取:
Scanner scanner = new Scanner(getClass().getResouceAsStream("hello.txt"));
Or if you're inside the staticcontext:
或者,如果您在static上下文中:
Scanner scanner = new Scanner(YourClass.class.getResouceAsStream("hello.txt"));
Where YourClassis the class in question.
YourClass有问题的班级在哪里。
回答by Steve Perkins
As has been pointed out, you could solve the problem by specifying an absolute path. However, you actually DO have some control over the current working directory from within the Java code. If the file you're reading is in the current working directory, then you could use this:
如前所述,您可以通过指定绝对路径来解决问题。但是,您实际上确实可以从 Java 代码内部控制当前工作目录。如果您正在阅读的文件在当前工作目录中,那么您可以使用:
Scanner scanner = new Scanner(
new File(System.getProperty("user.dir") + File.separatorChar +"hello.txt"));
The "user.dir" system level property contains the directory from which your application is running. Note that this ISN'T necessarily the directory in which the ".class" file resides. If that's what you're wanting, then the best approach would be loading it as a classpath resource (well covered in another answer.)
“user.dir”系统级属性包含运行应用程序的目录。请注意,这不一定是“.class”文件所在的目录。如果这就是您想要的,那么最好的方法是将其作为类路径资源加载(在另一个答案中有很好的介绍。)

