问题
I am trying to read a file in my java program called HelloJavaTest.java
but I keep on getting a FileNotFoundException
error.
The file I'm trying to import (hello.txt
) is in the same package as HelloJavaTest.java
(package: java_files).
Here is the message that pops up when I try to compile the code:
Exception in thread "main" java.io.FileNotFoundException: \java_files\hello.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at java.util.Scanner.<init>(Scanner.java:636)
at java_files.HelloJavaTest.main(HelloJavaTest.java:42)
Here is what I have at the top of my code:
import java.io.*; // for File
import java.util.Scanner;
回答1:
As the comments have correctly pointed that file reading and importing packages are not related.
Here \java_files\hello.txt
looks like the program is trying to find java_files
directory in the root directory \
, but is not able to find it.
You should not fiddle with paths if the file is located within the project.
Try using
URL url = Main.class.getClassLoader().getResource("test.txt");
System.out.println(url.getPath());
File f = new File(url.getPath());
Use the class loader to find the resource.
来源:https://stackoverflow.com/questions/13833814/if-the-file-i-am-trying-to-read-is-in-the-same-package-as-the-java-file-im-work