How to access a resource / configuration / text file in an external Jar from Java?

旧城冷巷雨未停 提交于 2019-12-06 13:39:10

问题


I am running a program in com.me.X.jar.

In an external com.me.Y.jar, I have a configuration file located at 'config/conf.txt' in the root of the Jar.

How can I access this configuration file programmatically from within Java?

com.me.Y.jar is not currently loaded in memory and is composed of just non-code resources.


回答1:


jar files are just zip files. So google for an example how to read a zip file. Or have a look at the API ZipInputStream




回答2:


The easiest option for reading embedded resources is to use Class.getResource or Class.getResourceAsStream

I can think of several ways to achieve this, depending on your needs.

Add the com.me.Y.jar to the classpath. You can do this either at the system level (not really recommended) or at the commend line...

java -cp com.me.Y.jar -jar com.me.X.jar

Edit It has being pointed at that apparently the -cp argument is ignored using the above command, but, if you include the main class it will work...java -cp com.me.Y.jar -jar com.me.X.jar com.me.x.Main (for example)

If that's inconvient, you can add com.me.Y.jar to com.me.X.jar manifest's class path which will automatically include com.me.Y.jar for you.

If you can't do that, you could use a URLClassLoader to directly load com.me.Y.jar...

URL[] urls = new URL[]{new File("/path/to/com.me.Y.jar").toURI().toURL())};
URLClassLoader classLoader = new URLClassLoader(urls);
URL resource = classLoader.findResource("/config/conf.txt");

Or, if you prefer, you could simply crack the Jar open using java.util.JarFile, but that seems a lot like cracking walnuts with a nuke...IMHO




回答3:


Code to obtain URL

URL configURL = this.getClass().getResource("/config/conf.txt");

Manifest.mf of com.me.X.jar

See Adding Classes to the JAR File's Classpath.

Main-Class: ...
Class-Path: com.me.Y.jar


来源:https://stackoverflow.com/questions/14408685/how-to-access-a-resource-configuration-text-file-in-an-external-jar-from-jav

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