Loading Resources from a JAR
When accessing resources embedded within a JAR archive, developers commonly encounter a discrepancy between the resource path obtained during IDE execution and when running the application via JAR. In the IDE's context, resources are accessed directly from the file system, while in the JAR environment, the path becomes jarringly adorned with the archive's prefix (e.g., "jar:/root/app.jar!/").
To resolve this issue and maintain a consistent resource access mechanism, heed the following advice:
Utilize getResourceAsStream
Eschew the temptation to load resources using FileInputStream or similar approaches. Instead, leverage the getResourceAsStream() method to retrieve a resource as an input stream, from which data can be conveniently read.
Avoid Direct File System Access
If your code relies on accessing resources as single files stored in the file system, refrain from packaging those resources within a JAR file. Consider an alternative arrangement, such as maintaining them as separate files.
Consider Temporary File Extraction
As a last resort, you might explore a hacky solution involving the following steps:
While this approach might be functional, its haphazard nature suggests it should be employed cautiously.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3