问题
Scanner Class couldnt find the file I use NetBeansIDE, and the test.txt is in the folder path: D:\netbeans project works\ReadFile\src\readfile\test.txt
in the same folder the readfile.java exsist. the code is as below. It generates file not found.
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());
}
}
output:-
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)
回答1:
Add the following before creating Scanner
class:
System.out.println(new File("test.txt").getAbsolutePath());
It will show you where JVM expects to find the file and whether it is the folder you expect as well.
Also check file permissions. But most likely it is a problem with default JVM directory.
回答2:
Ahhh you aren't specifying the full file path. When a file path is abbreviated (i.e. test.txt
), java assumes that the file is in the same directory as the source code that is running it. So either specify the full path, or move the file.
回答3:
Move it to the ReadFile directory, i.e. the root of the project
回答4:
The test.txt
file should be in the folder where the file readfile.class
exists.
回答5:
what worked for me was removing .txt extension from the file name and using . to specify current directory (example shown below).
Scanner scanner = new Scanner(new File("./test"));
来源:https://stackoverflow.com/questions/11385013/scanner-class-java-file-not-found