情景:本人在Windows下写了一个Java程序,该程序需要从当前目录下的一个.xml文件中读取参数。
问题在于现需把该程序打包成.jar包部署到Linux下,那么如何在Linux下定位当前目录呢?
参考网上的一些方法得知可以通过
String path = Class.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
来解决
请看两组实验:
程序代码如下:
package test;
public class T {
public static String path;
public static void main(String[] args) {
path = new T().getPath();
System.out.println(path);
}
public String getPath() {
String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
return path;
}
首先在windows下分别对.class和.jar文件进行测试(当前目录为G:/):
.class文件输出为:
/G:/
.jar文件输出为:
/G:/Test.jar
然后在Linux下分别对.class和.jar文件进行测试(当前目录为/usr/):
.class文件输出为:
/usr/
.jar文件输出为:
/usr/Test.jar
所以得出结论,对于.class文件或者在编译器中我们只需要去除最前面的'/'即可。而对于.jar而言,我们需要去除最前面的'/'和后面的jar包名.jar两部分才行。且为了保证在编译器中能够进行测试那么我们可以这样来写:
package test;
public class T {
public static String path;
public static void main(String[] args) {
path = new T().getPath();
}
public String getPath() {
String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
System.out.println(path);
if (System.getProperty("os.name").contains("dows")) {//判断操作系统
try {
path = java.net.URLDecoder.decode(path, "UTF-8");//防止Windows下中文目录乱码
} catch (Exception e) {
e.printStackTrace();
}
path = path.substring(1, path.length());//去除前'/'
}
if (path.contains("jar")) {//去除jar包名.jar
path = path.substring(0, path.lastIndexOf("."));
return path.substring(0, path.lastIndexOf("/"));
}
return path;
}
}