未找到Scanner类java文件

扫描程序类无法找到我使用NetBeansIDE的文件,而test.txt位于文件夹路径中:D:\ netbeans project works \ ReadFile \ src \ readfile \ test.txt

在readfile.java exsist的同一文件夹中。 代码如下。 它生成未找到的文件。

package readfile; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Scanner; public class ReadFile { public static void main(String[] args) throws IOException , FileNotFoundException { Scanner scanner = new Scanner(new File("test.txt")); while (scanner.hasNextLine()) System.out.println(scanner.nextLine()); } } 

输出: –

 run: Exception in thread "main" java.io.FileNotFoundException: test.txt (The system cannot find the file specified) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.(FileInputStream.java:106) at java.util.Scanner.(Scanner.java:636) at readfile.ReadFile.main(ReadFile.java:14) Java Result: 1 BUILD SUCCESSFUL (total time: 0 seconds) 

在创建Scanner类之前添加以下内容:

 System.out.println(new File("test.txt").getAbsolutePath()); 

它将向您显示JVM期望找到该文件的位置以及它是否是您期望的文件夹。

还要检查文件权限。 但很可能这是默认JVM目录的问题。

啊,你没有指定完整的文件路径。 当文件路径缩写(即test.txt )时,java假定该文件运行它的源代码位于同一目录中。 因此要么指定完整路径,要么移动文件。

将其移动到ReadFile目录,即项目的根目录

test.txt文件应位于文件readfile.class所在的文件夹中。

对我有用的是从文件名中删除.txt扩展名并使用。 指定当前目录(如下所示)。

 Scanner scanner = new Scanner(new File("./test"));