获得执行jar的运行路径-使用java.class.path 和 codesource的location

 

题记

上一篇使用了一个叫fat-jar的插件来制作jar包,确实很方便。但我们更容易遇到另一个更为棘手的问题!如何得到jar包的运行路径?

如果没有这个路径,我们读取文件可能找不到路径,写文件可能写到别的目录里了!

而且,调试代码时我们需要eclipse里的命令行里运行,而不需要打包;最终发布时我们需要打成jar包!所以,这部分代码应该要支持以上两种形式。

一般执行jar包有下面两种方式:

1、cd 到包含该jar包的目录里,执行命令
 

cd  E:\workspace4svn\Demorun\
java -jar  Demorun_fat.jar

2、直接加入绝对路径(比如把jar包直接拖入cmd窗口,就可以得到jar包的路径了)并执行命令
 

java -jar   E:\workspace4svn\Demorun\Demorun_fat.jar

所以,如果直接取相对路径就会得到两个结果,前者会是“E:\workspace4svn\Demorun\”,后者是"当前目录,如C:"。


解决办法

下面以一个jar包和一个data/in.txt为例来说明下面两种方法:

方法一:

System.getProperty("java.class.path")

在eclipse里运行(不打包)的结果是: “E:\workspace4svn\Demorun\bin;E:\workspace4svn\Hello\Hello_fat.jar” (注意:Hello_fat.jar不是可执行的jar,是从外部引入的包)

在cmd里运行jar包的结果是:“E:\workspace4svn\Demorun\Demorun_fat.jar”

[小结] 

(1) 这种方法在eclipse中运行结果的意思是"Path used to find directories and JAR archives containing class files.",也就是结果包括了可执行.class文件的路径以及引入的jar包路径

(2) 打包成jar包后,结果是jar包执行的路径!而且可以识别中文!

(3) 过于System.getProperty的用法参见http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html

参考代码如下中的getPath方法。

方法二:『力荐』

ClassName.class.getProtectionDomain().getCodeSource().getLocation().getPath()

在eclipse里运行(不打包)的结果是: “/E:/workspace/Demorun/bin/”

在cmd里运行jar包的结果是:“/E:/workspace/Demorun/Demorun_fat.jar”

如果不加.getPath,则结果是"file:/E:/workspace/Demorun/bin/"和"file:/E:/workspace/Demorun/Demorun_fat.jar",也就是说结果前面多了个"file:"

[小结]

(1) 这种方法不支持中文,需要转化下。

(2) 特别注意结果中的"斜线",方法一是windows中路径的正确表示,用""分割;方法二里是用"/"来分割,不是正确的路径!所以需要用file.getAbsolutePath();转化!

(3) 结果差异不大,在eclipse中的结果是.MainClass所在目录,而jar包运行的结果是jar包的完整路径。很容易可以得出程序运行的目录!具体程序如下:如getPath2()所示。

package system.property.java_class.path;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;


public class MyPath {

   
    public static String getPath(){
        String filePath=System.getProperty("java.class.path");
       
        String pathSplit=System.getProperty("path.separator");//windows下是; linux下是:
       
        if(filePath.contains(pathSplit)){
            filePath=filePath.substring(0, filePath.indexOf(pathSplit));
        }else if(filePath.endsWith(".jar")){//截取路径中的jar包名,可执行jar包运行结果包含.jar
            //此时的路径是"E:\workspace\Demorun\Demorun_fat.jar",用"/"(linux,unix)分割不行 
           //下面的语句输出是-1,应该改为lastIndexOf("\")或者lastIndexOf(File.separator) 
//          System.out.println("getPath2:"+filePath.lastIndexOf("/")); 
            filePath = filePath.substring(0, filePath.lastIndexOf(File.separator) + 1); 
            //File.separator:Character that separates components of a file path. This is "/" on UNIX and "" on Windows.
        }
        System.out.println(filePath);
        return filePath;
    }
   
   
    public static String getPath2(){
        //所有url都以file:/开始,以"/"作为分隔符末尾 并且以/作为末尾结束符
        URL url=MyPath.class.getProtectionDomain().getCodeSource().getLocation();
        String filePath=null;
        try {
            filePath=URLDecoder.decode(url.getPath(),"utf-8");//转化成utf-8编码
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
        if(filePath.endsWith(".jar")){//可执行jar包运行的结果包含".jar"
            // 截取路径中的jar包名 
            filePath=filePath.substring(0, filePath.lastIndexOf("/")+1);
        }
        File file=new File(filePath);
       
       
        filePath = file.getAbsolutePath();//得到windows下的正确路径 
        System.out.println(filePath);
        return filePath;
    }
    public static void main(String[] args){
        MyPath.getPath();
        MyPath.getPath2();
    }
}

 

总结:

在实际使用过程中,只需要使用上述两种方法中的一种即可!!

引用参考:blog.csdn.net/whuslei

原址:http://blog.sina.com.cn/s/blog_605f5b4f01010h6g.html