我正在尝试从jar文件访问资源。该资源位于jar所在的同一目录中。
I'm trying to access a resource from a jar file. The resource is located in the same directory where is the jar.
my-dir: tester.jar test.jpg我尝试了不同的东西,包括以下内容,但每次输入流为null :
I tried different things including the following, but every time the input stream is null:
[1]
String path = new File(".").getAbsolutePath(); InputStream inputStream = this.getClass().getResourceAsStream(path.replace("\\.", "\\") + "test.jpg");[2]
File f = new File(this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().getPath()); InputStream inputStream = this.getClass().getResourceAsStream(f.getParent() + "test.jpg");你能给我一些提示吗?谢谢。
Can you give me some hints? Thanks.
推荐答案如果您确定,您的应用程序的当前文件夹是jar的文件夹,您只需调用 InputStream f = new FileInputStream(test.jpg);
If you are sure, that your application's current folder is the folder of the jar, you can simply call InputStream f = new FileInputStream("test.jpg");
getResource 方法将使用类加载器加载东西,而不是通过文件系统。这就是你的方法(1)失败的原因。
The getResource methods will load stuff using the classloader, not through filesystem. This is why your approach (1) failed.
如果包含 * .jar 的文件夹和图像文件在类路径中,则可以获取图像资源好像它在默认包上:
If the folder containing your *.jar and image file is in the classpath, you can get the image resource as if it was on the default-package:
class.getClass().getResourceAsStream("/test.jpg");注意:图像现在已加载到类加载器中,只要应用程序运行,图像就会出现如果再次加载,则不会从内存中卸载并提供服务。
Beware: The image is now loaded in the classloader, and as long as the application runs, the image is not unloaded and served from memory if you load it again.
如果类路径中没有给出包含jar文件的路径,那么获取jarfile路径的方法是好。 然后直接通过URI直接访问该文件,打开一个流:
If the path containing the jar file is not given in the classpath, your approach to get the jarfile path is good. But then simply access the file directly through the URI, by opening a stream on it:
URL u = this.getClass().getProtectionDomain().getCodeSource().getLocation(); // u2 is the url derived from the codesource location InputStream s = u2.openStream();更多推荐
从jar访问jar外的资源
发布评论