我的代码在一个JAR文件中运行,比如foo.jar,我需要知道,在代码中,运行的foo.jar在哪个文件夹中。

所以,如果FOO .jar在C:\FOO\中,无论我当前的工作目录是什么,我都想获得这个路径。


当前回答

我用Java 7编写,用Oracle的运行时在Windows 7上测试,用开源运行时在Ubuntu上测试。这对于这些系统来说是完美的:

任何正在运行的jar文件的父目录的路径(假设调用这段代码的类是jar存档本身的直接子目录):

try {
    fooDir = new File(this.getClass().getClassLoader().getResource("").toURI());
} catch (URISyntaxException e) {
    //may be sloppy, but don't really need anything here
}
fooDirPath = fooDir.toString(); // converts abstract (absolute) path to a String

因此,foo.jar的路径是:

fooPath = fooDirPath + File.separator + "foo.jar";

同样,这也没有在任何Mac或旧版本的Windows上进行测试

其他回答

试试这个:

String path = new File("").getAbsolutePath();

你还可以使用:

CodeSource codeSource = YourMainClass.class.getProtectionDomain().getCodeSource();
File jarFile = new File(codeSource.getLocation().toURI().getPath());
String jarDir = jarFile.getParentFile().getPath();

对于一些愚蠢的简单的东西,你只需要这一行:

对于Windows用户,将“pwd”更改为“cd”

runCommand("pwd");

然后把这个方法扔到类中:

public static String runCommand(String command) {
    StringBuilder sb = new StringBuilder();
    try {
        ProcessBuilder pb = new ProcessBuilder(command);
        final Process p = pb.start();
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        sb.append(br.read());
        while ((line= br.readLine()) != null) sb.append(line).append("\n");
    }
    catch (IOException e) {e.printStackTrace();}
    return sb.toString();
}
public static String dir() throws URISyntaxException
{
    URI path=Main.class.getProtectionDomain().getCodeSource().getLocation().toURI();
    String name= Main.class.getPackage().getName()+".jar";
    String path2 = path.getRawPath();
    path2=path2.substring(1);

    if (path2.contains(".jar"))
    {
        path2=path2.replace(name, "");
    }
    return path2;}

在Windows上运行良好

getProtectionDomain方法有时可能不起作用,例如当你必须为一些核心java类(例如在我的情况下,IBM JDK中的StringBuilder类)找到jar时,但是下面的工作是无缝的:

public static void main(String[] args) {
    System.out.println(findSource(MyClass.class));
    // OR
    System.out.println(findSource(String.class));
}

public static String findSource(Class<?> clazz) {
    String resourceToSearch = '/' + clazz.getName().replace(".", "/") + ".class";
    java.net.URL location = clazz.getResource(resourceToSearch);
    String sourcePath = location.getPath();
    // Optional, Remove junk
    return sourcePath.replace("file:", "").replace("!" + resourceToSearch, "");
}