Abe*_*ojo 2 java readfile java.util.scanner
Scanner Class 找不到我使用 NetBeansIDE 的文件,test.txt 在文件夹路径中:D:\netbeans projectworks\ReadFile\src\readfile\test.txt
在同一个文件夹中存在 readfile.java。代码如下。它生成未找到的文件。
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 Code Online (Sandbox Code Playgroud)
输出:-
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.<init>(FileInputStream.java:106)
at java.util.Scanner.<init>(Scanner.java:636)
at readfile.ReadFile.main(ReadFile.java:14)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
Run Code Online (Sandbox Code Playgroud)
在创建Scanner类之前添加以下内容:
System.out.println(new File("test.txt").getAbsolutePath());
Run Code Online (Sandbox Code Playgroud)
它会告诉你 JVM 期望在哪里找到文件,以及它是否也是你期望的文件夹。
还要检查文件权限。但很可能是默认 JVM 目录的问题。