简体   繁体   中英

FIle Not Found exception while deploying Jar

I am getting File not found Exception to access files in File object from jar deployed after successful compilation.In this case files are placed in default folder of src and being access via src/filename.txt .

Even tried MyClass.class.getResource("/file.txt").getPath(); to access file 目录结构

File filterFile=new File("win.txt");
File currentFile=new File("winP.txt");

Kindly provide suggestion ie where to place text file in netbeans for jar deployment.

You need to distinguish between files and resources. Every file is also a resource, but not vice versa. Inside a JAR file, you do not have files, but only resources.

Loading resources is also done with a class loader. So you must first retrieve a class loader, then load the resource with it:

ClassLoader loader = Thread.currentThread().getContextClassLoader();
URL resourceUrl = loader.getResource(resourceName);
try (InputStream in = resourceUrl.openStream()) {
    // load bytes from the input stream here
}
// process the loaded resource bytes here

Now where to place the files? You could either place them into the root of the JAR. Inside your project, that means to place the resource file into the folder src . Or you place them into a package to have them beside the class that needs it.

If placed into the root, you access them via the resource name, only. If placed into a subdirectory (a package), you must prefix the resource name with that path - beginngin from the root. Example:

URL resourceUrl = loader.getResource("my/pkg/win.txt");

Just a convenience: If the resource file is placed into the same package as the class that is needing that resource, you could also use the class itself for loading (and not the class loader):

URL resourceUrl = getClass().getResource("win.txt");

Note, that in this case, the directory structure is omitted.

In your example, you created a file object. If you used that file object to create a FileInputStream later, then you can just use the InputStream , which I described above, instead of that.

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