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

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


当前回答

上述方法在我的Spring环境中并不适用,因为Spring将实际的类隐藏到一个名为BOOT-INF的包中,因此不是运行文件的实际位置。我发现了另一种方法来检索运行文件通过权限对象已授予运行文件:


public static Path getEnclosingDirectory() {
    return Paths.get(FileUtils.class.getProtectionDomain().getPermissions()
            .elements().nextElement().getName()).getParent();
}

其他回答

你还可以使用:

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

我有另一种方法来获取类的String位置。

URL path = Thread.currentThread().getContextClassLoader().getResource("");
Path p = Paths.get(path.toURI());
String location = p.toString();

输出字符串的形式为

C:\Users\Administrator\new Workspace\...

空格和其他字符被处理,并且在没有file:/的形式。这样会更容易使用。

return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation()
    .toURI()).getPath();

将“MyClass”替换为类名。

显然,如果您的类是从非文件位置加载的,这将会做一些奇怪的事情。

试试这个:

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

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

对于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();
}