如何在JAR之外加载文件,但相对于JAR? [英] How to Load File Outside of, but Relative to, the JAR?

查看:100
本文介绍了如何在JAR之外加载文件,但相对于JAR?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在JAR之外加载一个文件,但相对于它(确切地说是 lib / config / config.ini )。我使用了那个确切的路径,只要工作目录是JAR所在的地方就可以正常工作,即

I need to load a file outside of the JAR, but relative to it (lib/config/config.ini to be exact). I used that exact path, and it works fine as long as the working directory is where the JAR is, i.e.

/path/to/jar$ java -jar JAR.jar

如果它像这样运行:

~$ java -jar /path/to/jar/JAR.jar

找不到它。如何正确加载相对于JAR位置的文件?

It can't find it. How can I correctly load a file relative to the location of the JAR?

推荐答案

尝试使用 getClassLoader( ).getResource(classname)在jar文件中查找类的URL。你会发现它在jar路径和jar中的路径之间用分隔,你可以轻松切片。

Try using getClassLoader().getResource("classname") to find the URL of a class in your jar file. You'll find it's delimited with a ! between the path to the jar, and the path within a jar, which you can easily slice.

这篇关于如何在JAR之外加载文件,但相对于JAR?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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