14

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

したがって、基本的には、ClassPath ではなく、ファイル名のない JAR ファイルのパスが必要です。

これを行う方法はありますか?

4

4 に答える 4

29

アップデート

特定のテストケースでは機能しないため、回答を更新します。

これを行う正しい方法は、次のようにする必要があります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
于 2013-03-12T11:32:08.653 に答える
20

これで、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());
    }
}
于 2014-01-06T15:34:09.000 に答える
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に基づいて文字列をトークン化し、.jarを含むトークンを取得するまで、(文字列をFile.separatorで連結して)パスを作成します。

于 2013-03-12T11:28:05.670 に答える