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

Bob*_*Bob 0 java

我有以下情况

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

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

Bal*_*usC 5

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

Scanner scanner = new Scanner(new File("/full/path/to/hello.txt"));
Run Code Online (Sandbox Code Playgroud)

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


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

Scanner scanner = new Scanner(getClass().getResouceAsStream("hello.txt"));
Run Code Online (Sandbox Code Playgroud)

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

Scanner scanner = new Scanner(YourClass.class.getResouceAsStream("hello.txt"));
Run Code Online (Sandbox Code Playgroud)

YourClass有问题的班级在哪里.