如何获取运行java程序的路径 [英] How to get the path of running java program

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

问题描述

有没有办法获取正在运行的java程序的主类的路径.

Is there a way to get the path of main class of the running java program.

结构是

D:/
|---Project
       |------bin
       |------src

我想将路径设为 D:Projectin.

我试过 System.getProperty("java.class.path"); 但问题是,如果我像

I tried System.getProperty("java.class.path"); but the problem is, if I run like

java -classpath D:Projectin;D:Projectsrc  Main

Output 
Getting : D:Projectin;D:Projectsrc
Want    : D:Projectin

有没有办法做到这一点?

Is there any way to do this?

===== 编辑 =====

这里有解决方案

解决方案 1(来自 乔恩·斯基特)

package foo;

public class Test
{
    public static void main(String[] args)
    {
        ClassLoader loader = Test.class.getClassLoader();
        System.out.println(loader.getResource("foo/Test.class"));
    }
}

打印出来:

file:/C:/Users/Jon/Test/foo/Test.class


解决方案 2(来自 埃里克森)

URL main = Main.class.getResource("Main.class");
if (!"file".equalsIgnoreCase(main.getProtocol()))
  throw new IllegalStateException("Main class is not stored in a file.");
File path = new File(main.getPath());

请注意,大多数类文件都被组装到 JAR 文件中,因此这不会在所有情况下都有效(因此出现 IllegalStateException).但是,您可以使用这种技术定位包含类的 JAR,并且您可以通过调用 getResourceAsStream() 代替 getResource()<来获取类文件的内容/code>,无论该类是在文件系统中还是在 JAR 中,这都将起作用.

Note that most class files are assembled into JAR files so this won't work in every case (hence the IllegalStateException). However, you can locate the JAR that contains the class with this technique, and you can get the content of the class file by substituting a call to getResourceAsStream() in place of getResource(), and that will work whether the class is on the file system or in a JAR.

推荐答案

试试这个代码:

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

用包含 main 方法的类替换MyClass".

replace 'MyClass' with your class containing the main method.

或者你也可以使用

System.getProperty("java.class.path")

上面提到的系统属性提供

Above mentioned System property provides

用于查找包含类文件的目录和 JAR 档案的路径.类路径的元素由特定于平台的path.separator 属性中指定的字符.

Path used to find directories and JAR archives containing class files. Elements of the class path are separated by a platform-specific character specified in the path.separator property.

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

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