情景:本人在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
<