When loading resources, if an application is run from an IDE, the path to the resource may be different than when run from a jar file. This can cause problems if the application relies on the specific file path.
One way to solve this problem is to use getResourceAsStream instead of getResource. getResourceAsStream returns an InputStream, which can be used to read the resource data without having to deal with the file path.
Another option is to extract the resource to a temporary file before using it. This can be done using the Files.copy method.
However, it is important to note that some code may rely on the data being in a physical single file in the file system. In this case, bundling the resource in a jar file may not be an option.
Code Sample:
InputStream inputStream = WinProcessor.class.getResourceAsStream("repository"); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { // Do something with the line } reader.close();
The above is the detailed content of How to Load Resources Correctly from a Jar File?. For more information, please follow other related articles on the PHP Chinese website!