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”?

坚强是说给别人听的谎言 提交于 2019-12-13 21:04:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!