读取文件错误:找不到文件

时间:2010-09-30 21:49:56

标签: java

我有以下

 Scanner scanner = new Scanner(new File("hello.txt"));
   while(scanner.hasNextInt()){
       int i = scanner.nextInt();
       System.out.println(i);
    }

运行时为什么会出错?它在file not found (The system cannot find the files specificed)中说java.io.fileinputstream。但该文件确实存在。

2 个答案:

答案 0 :(得分:5)

您需要指定绝对路径。现在,您正在指定相对路径。该路径相对于当前工作目录,您无法在Java代码中对其进行控制。相对路径取决于您执行Java代码的方式。在命令提示符下,它是当前打开的文件夹。在像Eclipse这样的IDE中,它是项目的根文件夹。在Web应用程序中,它是服务器的二进制文件夹等。

Scanner scanner = new Scanner(new File("/full/path/to/hello.txt"));

在Windows环境中,上面的示例等于C:\full\path\to\hello.txt


如果您的实际意图是将此文件放在当前正在运行的类的同一文件夹中,那么您应该将其作为类路径资源获取:

Scanner scanner = new Scanner(getClass().getResouceAsStream("hello.txt"));

或者如果你在static上下文中:

Scanner scanner = new Scanner(YourClass.class.getResouceAsStream("hello.txt"));

YourClass是哪个类。

答案 1 :(得分:0)

正如已经指出的那样,您可以通过指定绝对路径来解决问题。但是,您实际上可以从Java代码中控制当前工作目录。如果您正在阅读的文件位于当前工作目录中,那么您可以使用:

Scanner scanner = new Scanner(
    new File(System.getProperty("user.dir") + File.separatorChar +"hello.txt"));

“user.dir”系统级属性包含运行应用程序的目录。请注意,这不一定是“.class”文件所在的目录。如果那就是你想要的,那么最好的方法是将它作为类路径资源加载(在另一个答案中有很好的介绍。)

相关问题