开发者

FileNotFoundException in Netbeans

I have a java application project in Netbeans. I have just one class. I try to do this

FileReader fr = new FileReader("sal.html");

I have the file sal.html under the same package. But I get this error when I run:

Errorjava.io.FileNotFoundException: sal.html (The system cannot find th开发者_如何学运维e file specified)


My guess is that Netbeans is invoking the JVM from your project's root folder. Quoting a portion of the File Javadoc:

By default the classes in the java.io package always resolve relative pathnames against the current user directory. This directory is named by the system property user.dir, and is typically the directory in which the Java virtual machine was invoked.

To verify relative path resolution you could try:

System.out.println(System.getProperty("user.dir"));
System.out.println(new File("sal.html").getAbsolutePath());

You could then move your file to wherever java is looking for it. Most probably your project's root folder.

You could also consider using the class loader to read files as resources inside packages using getClass().getResourceAsStream("sal.html");. This is the preferred way of accessing resources since you no longer have to worry about absolute vs. relative paths. If a resource is in your classpath, you can access it. See this answer for more.


Put your file to main project folder. Not to any sub folders like src, or bin etc. Then it will detect your file.


Click on file view in Netbeans. Move sal.html to the project folder. Such that you will see it like this

- JavaProject
  + build
  + lib
  + nbproject
  + src
  + build.xml
  manifest.mf
  sal.html

Now

FileReader fr = new FileReader("sal.html");

will work.


System.out.println(System.getProperty("user.dir"));
System.out.println(new File("sal.html").getAbsolutePath());

Then it will show where the JVM is retrieving the files from. Usually for linux in the /home/username/NetbeansProjects/ApplicationName/.

Put your resources or files to this path


I think your problem is in the relative path to the file. Try to declare FileReader with full path to file.


FileNotFoundException means file not found.

The build folder for the netbeans is different where there is no file sal.html.

Try using absolute path in place of using relative path.


This is not a "File not found" problem. This is because each class hold its own resources (let it be file, image etc.) which can be accessed only through a resource loader statement which is as below:

InputStream in = this.getClass().getResourceAsStream("sal.html");

The only fix is that you will get an InputStream instead of a file. Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜