linux下的当前目录,Linux下定位当前目录

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

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值