获取JAR文件的位置

时间:2013-03-12 11:18:12

标签: java class jar path directory

我正在尝试从运行Runnable JAR文件获取该位置。 我试着做了

try {
    String path = new java.io.File(".").getCanonicalPath();
} catch (IOException e) {
    e.printStackTrace();
}

但是回归:

C:\Users\Kevin\Desktop/server/Server

,而JAR文件位于

C:\Users\Kevin\Desktop

我也尝试过做

return new file(Server.class.getProtectionDomain().getCodeSource().getLocation().getPath());

但是回归:

C:\Users\Kevin\Desktop\server.jar/server/Server

基本上我想要JAR文件的路径没有文件名而不是ClassPath。

任何方式这样做?

4 个答案:

答案 0 :(得分:25)

<强>更新

由于它在某些测试用例中不起作用,我会更新答案。

执行此操作的正确方法应该是ClassLoader

File jarDir = new File(ClassLoader.getSystemClassLoader().getResource(".").getPath());
System.out.println(jarDir.getAbsolutePath());

在各种类路径上测试,输出正确。


旧答案

这应该有效

File f = new File(System.getProperty("java.class.path"));
File dir = f.getAbsoluteFile().getParentFile();
String path = dir.toString();

它对我有用,我的程序在:

C:\Users\User01\Documents\app1\dist\JavaApplication1.jar

它返回

C:\Users\User01\Documents\app1\dist

答案 1 :(得分:17)

这是我计算jar目录的版本

/**
 * Compute the absolute file path to the jar file.
 * The framework is based on http://stackoverflow.com/a/12733172/1614775
 * But that gets it right for only one of the four cases.
 * 
 * @param aclass A class residing in the required jar.
 * 
 * @return A File object for the directory in which the jar file resides.
 * During testing with NetBeans, the result is ./build/classes/,
 * which is the directory containing what will be in the jar.
 */
public static File getJarDir(Class aclass) {
    URL url;
    String extURL;      //  url.toExternalForm();

    // get an url
    try {
        url = aclass.getProtectionDomain().getCodeSource().getLocation();
          // url is in one of two forms
          //        ./build/classes/   NetBeans test
          //        jardir/JarName.jar  froma jar
    } catch (SecurityException ex) {
        url = aclass.getResource(aclass.getSimpleName() + ".class");
        // url is in one of two forms, both ending "/com/physpics/tools/ui/PropNode.class"
        //          file:/U:/Fred/java/Tools/UI/build/classes
        //          jar:file:/U:/Fred/java/Tools/UI/dist/UI.jar!
    }

    // convert to external form
    extURL = url.toExternalForm();

    // prune for various cases
    if (extURL.endsWith(".jar"))   // from getCodeSource
        extURL = extURL.substring(0, extURL.lastIndexOf("/"));
    else {  // from getResource
        String suffix = "/"+(aclass.getName()).replace(".", "/")+".class";
        extURL = extURL.replace(suffix, "");
        if (extURL.startsWith("jar:") && extURL.endsWith(".jar!"))
            extURL = extURL.substring(4, extURL.lastIndexOf("/"));
    }

    // convert back to url
    try {
        url = new URL(extURL);
    } catch (MalformedURLException mux) {
        // leave url unchanged; probably does not happen
    }

    // convert url to File
    try {
        return new File(url.toURI());
    } catch(URISyntaxException ex) {
        return new File(url.getPath());
    }
}

答案 2 :(得分:0)

在我找到一个有效的解决方案之前,我不得不捣乱。
jarLocation可能会带有file:\jar:file\这样的前缀,可以使用String#substring()删除。

URL jarLocationUrl = MyClass.class.getProtectionDomain().getCodeSource().getLocation();
String jarLocation = new File(jarLocationUrl.toString()).getParent();

答案 3 :(得分:-1)

如果你知道

file(Server.class.getProtectionDomain().getCodeSource().getLocation().getPath());

返回

C:\Users\Kevin\Desktop\server.jar/server/Server

而且你知道你的Jar名称是server.jar或者任何.jar文件,你的意图是获得C:\ Users \ Kevin \ Desktop,直接的方法就是进行字符串操作。

使用检索到的输出,基于File.separator对字符串进行标记化并构造路径(通过将字符串与File.separator连接在一起),直到获得包含.jar的标记