如何知道java中jar文件的目录? [英] How to know the directory of jar file in java?

查看:131
本文介绍了如何知道java中jar文件的目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可执行的jar文件,我希望它能够读取和写入与.jar文件位于同一目录的txt文件的信息。我怎样才能做到这一点?如何获取可执行jar文件目录路径。它只需要在Windows平台上工作,它就是桌面应用程序。

I have an executable jar file and I want it to be able to read and write info to a txt file that is located at the same dir as the .jar file is. How can I do that? How can I get the executable jar file dir path. It only has to work on windows platform and it's a desktop application.

推荐答案

以下代码片段将为您完成此任务:

The following code snippet will do this for you:

final File f = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());

用您的<替换 MyClass code> main class

replace MyClass with your main class

生成的文件对象 f 表示已执行的 .jar 文件。
您可以使用此对象获取文件所在的目录,并使用它来构建目录路径。

The resulting File object f represents the .jar file that was executed. You can use this object to get the directory the file is in and use that to build a directory path.

这篇关于如何知道java中jar文件的目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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