如果我要读取的文件与我正在使用的Java文件位于同一包中,为什么仍会收到“ FileNotFoundException”? [英] If the file I am trying to read is in the same package as the java file I'm working with, why am I still getting a "FileNotFoundException"?
问题描述
我试图在我的Java程序中读取名为 HelloJavaTest.java
的文件,但我一直在获取 FileNotFoundException
错误。
I am trying to read a file in my java program called HelloJavaTest.java
but I keep on getting a FileNotFoundException
error.
我要导入的文件( hello.txt
)与<$ c在同一软件包中$ c> HelloJavaTest.java (程序包:java_files)。
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;
推荐答案
注释已正确指出文件读取和导入包无关。
As the comments have correctly pointed that file reading and importing packages are not related.
此处 \java_files\hello.txt
似乎程序正在尝试查找根目录 \
中的 java_files
目录,但找不到它。
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.
尝试使用
URL url = Main.class.getClassLoader().getResource("test.txt");
System.out.println(url.getPath());
File f = new File(url.getPath());
使用类加载器查找资源。
这篇关于如果我要读取的文件与我正在使用的Java文件位于同一包中,为什么仍会收到“ FileNotFoundException”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!