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

人盡茶涼 提交于 2019-12-04 19:05:43

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

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

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