如何得到运行 Java 程序的路径

有没有一种方法可以得到正在运行的 Java 程序的主类的路径。

结构是

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

我想得到的路径作为 D:\Project\bin\

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

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


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

有什么办法吗?



= = = = = = EDIT = = = = =

这里有 解决方案

解决方案1 (通过 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


解决方案2 (通过 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()代替 getResource()来获得类文件的内容,这样无论类是在文件系统中还是在 JAR 中都可以工作。

339389 次浏览
    ClassLoader cl = ClassLoader.getSystemClassLoader();


URL[] urls = ((URLClassLoader)cl).getURLs();


for(URL url: urls){
System.out.println(url.getFile());
}

Try this code:

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

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

Alternatively you can also use

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

Above mentioned System property provides

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.

You actually do not want to get the path to your main class. According to your example you want to get the current working directory, i.e. directory where your program started. In this case you can just say new File(".").getAbsolutePath()

Use

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

see http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html

You can also split it into it's elements easily

String classpath = System.getProperty("java.class.path");
String[] classpathEntries = classpath.split(File.pathSeparator);