如何从 Java JAR 文件中获取资源/文件的路径

发布于 2024-09-27 08:54:09 字数 330 浏览 2 评论 0原文

我正在尝试获取位于 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

只是在用心讲痛 2024-10-04 08:54:09

如果文件与 jar 位于同一目录中,我认为这会起作用(感觉相当 hacky,但是......):(

URL url = getClass().getProtectionDomain().getCodeSource().getLocation();
File myfile = new File(url.toURI());
File dir = myfile.getParentFile(); // strip off .jar file

还没有测试过这个,但它似乎可行。当然仅适用于基于文件的 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...):

URL url = getClass().getProtectionDomain().getCodeSource().getLocation();
File myfile = new File(url.toURI());
File dir = myfile.getParentFile(); // strip off .jar file

(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 use getResource().)

万劫不复 2024-10-04 08:54:09

这样做不会

     File FileName = new File(".");
     String Directory = FileName.getCanonicalPath();

让你在文件或 jar 中获得类的父目录,只要记住设置目录(如果它位于像这样的 jar 中)“NameOfJar\NameOfFolder\etc”

No just do

     File FileName = new File(".");
     String Directory = FileName.getCanonicalPath();

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"

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文