简体   繁体   English

如何从Java访问外部Jar中的资源/配置/文本文件?

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

I am running a program in com.me.X.jar . 我正在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. 在外部com.me.Y.jar中 ,我在Jar根目录中的' config / conf.txt '中有一个配置文件。

How can I access this configuration file programmatically from within Java? 如何在Java中以编程方式访问此配置文件?

com.me.Y.jar is not currently loaded in memory and is composed of just non-code resources. com.me.Y.jar当前未加载到内存中,仅由非代码资源组成。

jar files are just zip files. jar文件只是zip文件。 So google for an example how to read a zip file. 所以谷歌为例,如何读取一个zip文件。 Or have a look at the API ZipInputStream 或看看API ZipInputStream

The easiest option for reading embedded resources is to use Class.getResource or Class.getResourceAsStream 读取嵌入式资源的最简单选择是使用Class.getResourceClass.getResourceAsStream

I can think of several ways to achieve this, depending on your needs. 我可以根据您的需要考虑几种实现此目的的方法。

Add the com.me.Y.jar to the classpath. com.me.Y.jar添加到类路径。 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) 编辑已经指出,显然-cp参数使用上述命令被忽略了,但是,如果包含主类,它将起作用... java -cp com.me.Y.jar -jar com.me.X.jar com.me.x.Main (例如)

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. 如果com.me.Y.jar ,可以将com.me.Y.jar添加到com.me.X.jar 清单的类路径中 ,该路径将自动为您包括com.me.Y.jar

If you can't do that, you could use a URLClassLoader to directly load com.me.Y.jar ... 如果无法做到这一点,则可以使用URLClassLoader直接加载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 或者,如果愿意,您可以使用java.util.JarFile轻松打开Jar,但这似乎很像用核子将核桃开裂...恕我直言

Code to obtain URL 获取网址的代码

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

Manifest.mf of com.me.X.jar com.me.X.jar Manifest.mf

See Adding Classes to the JAR File's Classpath . 请参阅将类添加到JAR文件的类路径中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM