如何从 Java JAR 文件中获取资源/文件的路径
我正在尝试获取位于 java jar 之外的文件的路径,但我不想使用绝对路径。一个例子:假设 jar 位于 ~/lib/myjar.jar 中,并且该文件位于同一文件夹中。我尝试的是这样的,但失败了:
File myfile = new File(this.getClass().getResource("../../../").toURI());
注意:我的包是 com.contro.gui,这就是为什么我有“../../../”,以便访问“root”
我不确定如何访问该文件。有什么建议吗??如果我要访问的文件位于 ~/res/ 这样的其他文件夹中怎么办?
I'm trying to get the path to a file that it is located out of the java jar and I don't want to use an absolute path. An exampel: lets say that the jar is located in ~/lib/myjar.jar and the file is located in the same folder. What I've trying is something like this, but it fails:
File myfile = new File(this.getClass().getResource("../../../").toURI());
Note: my package is com.contro.gui, that's why I have "../../../", in order to acces to the "root"
I'm not sure how I can access to the file. Any suggestion?? And what about if the file that I want to access is in other folder like ~/res/ ???
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果文件与 jar 位于同一目录中,我认为这会起作用(感觉相当 hacky,但是......):(
还没有测试过这个,但它似乎可行。当然仅适用于基于文件的 jar )。
如果文件位于某个随机位置,我认为您需要传递参数或检查“已知”位置,例如
user.home
。 (或者,您始终可以使用getResource()
将文件放入 jar 中。)If the file is in the same directory as the jar, I think this will work (feels fairly hacky, but...):
(Haven't tested this, but it seems feasible. Will only work with file-based jars of course).
If the file is in some random location, I think you will need to either pass in parameters or check "known" locations like
user.home
. (Or, you could always put the file in the jar a usegetResource()
.)这样做不会
让你在文件或 jar 中获得类的父目录,只要记住设置目录(如果它位于像这样的 jar 中)“NameOfJar\NameOfFolder\etc”
No just do
that will get you the parent directory of your class in a file or jar just remember to set the directory if it's in a jar like this "NameOfJar\NameOfFolder\etc"