问题描述
在 java中, System.getProperty("user.dir") 得到的是当前工作路径(对应命令行命令就是 linux 下的 pwd 、windows 下的 cd ),而 System.getProperty("user.home") 得到的是当前用户主目录(对应于 linux 下的 ~ 目录、windows 下的 document and settings\username );但如果你想得到所运行的 java 程序所在的路径,似乎并没有什么简单的方法。
比如说,有一个 pathTest.jar包放在 D:\zwb\test 下,这个 jar 执行的时候需要在当前目录下读写一个 test.xml 文件。如果不采用绝对路径来读写 test. xml 的话,不同的 jar 运行方式会带来不同的结果:
cd D: \zwb\test
java -jar pathTest.jar
( test.xml将生成在 D:\zwb\test目录下 )
cd E:\sun\jre\bin
java -jar D: \zwb\test\pathTest.jar
( test.xml将生成在 E:\sun\jre\bin目录下 )
这势必造成潜在的运行错误。解决的方法是必须在程序中指定 test.xml文件的绝对路径。从本意上来讲,这里我们希望 test. xml 与 pathTest.jar 位于相同的路径之下。但显然无论是 "user.dir" 还是"user.home" 都不会返回正确的结果。
解决办法
方法一:
System.getProperty("java.class.path");
方法二:
ClassName.class.getProtectionDomain().getCodeSource().getLocation().getPath();
参考代码如下:
import java.io.File;
import java.net.URL;
import java.net.URLDecoder;
public class GetPathUtil {
/**
* 方法一
* (1) 这种方法在eclipse中运行结果的意思是"Path used tofind directories and JAR archives containing class files.",也就是结果包括了可执行.class文件的路径以及引入的jar包路径。
* (2) 打包成jar包后,结果是jar包执行的路径!而且可以识别中文!
* @return
*/
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"
filePath = filePath.substring(0, filePath.lastIndexOf(File.separator)+ 1);
}
return filePath;
}
/**
* 方法二
* (1) 这种方法不支持中文,需要转化下。
* (2) 特别注意结果中的"斜线",方法一是windows中路径的正确表示,用"\"分割;方法二里是用"/"来分割,不是正确的路径!所以需要用file.getAbsolutePath();转化!
* (3) 结果差异不大,在eclipse中的结果是.MainClass所在目录,而jar包运行的结果是jar包的完整路径。很容易可以得出程序运行的目录!具体程序如下:
* @return
*/
public static String getPath2() {
URLurl= GetPathUtil.class.getProtectionDomain().getCodeSource().getLocation();
String filePath = null;
try {
filePath = URLDecoder.decode(url.getPath(), "utf-8");// 转化为utf-8编码
} catch (Exception e) {
e.printStackTrace();
}
if (filePath.endsWith(".jar")) {// 可执行jar包运行的结果里包含".jar"
// 截取路径中的jar包名
filePath = filePath.substring(0, filePath.lastIndexOf("/") + 1);
}
File file = new File(filePath);
// /If this abstract pathname is already absolute, then the pathname
// string is simply returned as if by the getPath method. If this
// abstract pathname is the empty abstract pathname then the pathname
// string of the current user directory, which is named by the system
// property user.dir, is returned.
filePath = file.getAbsolutePath();//得到windows下的正确路径
return filePath;
}
public static void main(String[] args) {
System.out.println(getPath());
System.out.println(getPath2());
}
}