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

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

问题描述

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

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

结构是

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

我想把路径改为 D:\Project \ bin \

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

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

java -classpath D:\Project\bin;D:\Project\src\  Main

Output 
Getting : D:\Project\bin;D:\Project\src\
Want    : D:\Project\bin

有没有办法做到这一点?

Is there any way to do this?

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

在这里解决方案

Jon Skeet

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


Erickson

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()来代替<来获取类文件的内容。 code> getResource(),无论该类是在文件系统上还是在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());

用您的类替换' 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天全站免登陆