使用jar作为资源存档的简单方法 [英] Simple way to use a jar as a resource archive

查看:99
本文介绍了使用jar作为资源存档的简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我正在研究一个Java应用程序,我想将资源打包到jar文件中,以使它们更具可移植性。这些jar文件将与应用程序分开,并且只包含资源(图像,声音,保存文件等)。

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).

从内部访问任意资源的最简单方法是什么像这样的jar文件?我看了一下,但一直找不到任何简单的教程。我知道我可以使用ClassLoader从Jar文件中检索输入流但是如何获得引用正确Jar的ClassLoader?

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?

此外,我如何以编程方式捆绑一堆资源进入这样的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.

推荐答案

为了阅读资源,构建一个新的 URLClassLoader ,其中包含您要加载的JAR的URL:

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()});

要创建JAR文件,可以使用 JarOutputStream 类。

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

这篇关于使用jar作为资源存档的简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆