如何获取执行.jar文件的路径? [英] How to get the path of executed .jar file?

查看:153
本文介绍了如何获取执行.jar文件的路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Java中获取已执行的.jar文件的路径?

How do I get the path of a an executed .jar file, in Java?

我尝试使用 System.getProperty(user .dir); 但这只给了我当前的工作目录,这是错误的,我需要目录的路径,.jar文件直接位于,而不是pwd。

I tried using System.getProperty("user.dir"); but this only gave me the current working directory which is wrong, I need the path to the directory, that the .jar file is located in, directly, not the "pwd".

推荐答案

你能说明你需要路径的原因吗?
如果你需要从jar文件中访问一些属性你应该看看ClassLoader.getSystemClassLoader();

不要忘记你的类不必存储在jar文件中。

Could you specify why you need the path?
If you need to access some property from the jar file you should have a look at ClassLoader.getSystemClassLoader();
don't forget that your classes are not necessary store in a jar file.


// if your config.ini file is in the com package.
URL url = getClass().getClassLoader().getResource("com/config.ini");
System.out.println("URL=" + url);

InputStream is = getClass().getClassLoader().getResourceAsStream("com/config.ini");
try {
    if (is != null) {
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    }
    else {
        System.out.println("resource not found.");
    }
}
catch (IOException e) {
    e.printStackTrace();
}

问候。

这篇关于如何获取执行.jar文件的路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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