获取JAR文件的位置(Get location of JAR file)

2019-07-21 10:01发布

我试图让一个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

所以basicly我想要的JAR文件不带文件的路径,而不是类路径。

这样做的方法吗?

Answer 1:

更新

因为它并不在某些测试情况下工作,我会更新的答案。

正确的方式做,这应该是与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


Answer 2:

特此我的版本计算的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());
    }
}


Answer 3:

我只好勾搭了很多之前,我终于找到一个可行的解决方案。
可能的是,所述jarLocation带有像前缀file:\jar:file\ ,它可通过使用被移除String#substring()

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


Answer 4:

如果你知道的话

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

回报

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

你知道你的JAR的名字是的server.jar或事项的任何.jar文件,你的本意是让C:\用户\凯文\桌面,直接的方式就是做字符串操作。

与检索到的输出,令牌化基于文件分割符串和构建路径(通过连接与文件分割符的字符串之间),直到你得到它包含的.jar令牌



文章来源: Get location of JAR file