简体   繁体   中英

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 the 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.

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM