Simple way to use a jar as a resource archive

与世无争的帅哥 提交于 2020-01-07 03:10:23

问题


So, I'm working on a Java application and I'd like to package resources into jar files to make them more portable. These jar files would be separate from the application and would only contain assets (images, sounds, save files, etc).

What's the simplest way to access arbitrary resources from inside a jar file like this? I've looked around a bit, but haven't been able to find any simple tutorials. I know that I can retrieve input streams from a Jar file with a ClassLoader but how do I get a ClassLoader that references the correct Jar?

Also, how can I programmatically bundle a bunch of resources into such a jar file? If I can get this working the way I want, I'd like to use it for a bunch of stuff, and would like to be able to dynamically create any needed archives.


回答1:


For reading resources, construct a new URLClassLoader with the URLs of the JARs you want to load from:

File jarFile1 = new File("myjar.jar");
File jarFile2 = new File("myjar2.jar");
ClassLoader myJarLoader = URLClassLoader.newInstance(new URL[] {jarFile1.toURI().toURL(), 
                                                                jarFile2.toURI().toURL()});

For creating JAR files, you can use the JarOutputStream class.




回答2:


I jar file is in classpath Thread.currentThread().getContextClassLoader().getResourceAsStream(path/file.ext) will load the resource by name.

jar -cvf jarname.jar resource

will add all the resources to jarname.jar, try using ZipOutputStream to programatically achieve the same.




回答3:


Shouldn't be a problem to use getResourceAsStream with the resource package path, provided that the jar with the resources is in the classpath of your application

A way to automatically create the resource.jar from your binaries is using apache ant for building, using a target like the following, you will take every res package resources and copy it into the destination jar

<property name="binDir" value="bin" />
...

<target name="resources-jar">
    <echo message="Generating resources.jar" />
    <jar compress="true" destfile="resources.jar" filesetmanifest="mergewithoutmain">
        <fileset defaultexcludes="true" dir="${binDir}"> 
            <include name="**/res/**" />              
        </fileset>
    </jar>
</target>  

For example, due the following packages

 com/myapp/logic 
 com/myapp/logic/res
 com/myapp/menu
 com/myapp/menu/res 
 com/myapp/actions
 com/myapp/actions/res

The resource.jar file will contain the following packages:

 com/myapp/logic/res
 com/myapp/menu/res 
 com/myapp/actions/res

Also you can change res for assets



来源:https://stackoverflow.com/questions/11044353/simple-way-to-use-a-jar-as-a-resource-archive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!