java 获取绝对路径方式

最近项目中需要使用获取操作系统路径问题,刚开始使用的是System.getProperty("user.dir")获取相对路径,但是这存在一个问题就是,我们使用shell脚本启动的时候,
如果启动的地方在其他地方,获取的路径地址就会在当前路径,而不是文件路径所在的位置。
如: 如果,启动的时候,直接在msgplus下面启动路径地址就在/home/msgplus下面,但是如果使用sh /home/msgplus/startup.sh启动,路径就在与home平级的目录。
于是到网上进查找资料,找了半天找到一些资料,终于可以完成本人所需要的功能,
现把此功能的核心部分写出来,
/**
* 获取路径
* @author liujunliang
* @creaetime Jul 2, 2011 9:55:25 AM
* @param cls 类位置
* @return String 返回值
* @throws IOException 异常
*/
public String getPathFromClass(Class cls) throws Exception {
String path = null;
if (cls == null) {
throw new NullPointerException();
}
URL url = getClassLocationURL(cls);
if (url != null) {
path = url.getPath();
path = java.net.URLDecoder.decode(url.getPath(), "utf-8");
File file = new File(path.replaceAll("%20", " "));
path = file.getCanonicalPath();
}
return path;
}

/**
* 获取类的class文件位置的URL。这个方法是本类最基础的方法,供其它方法调用。
* @author liujunliang
* @creaetime Jul 2, 2011 9:59:39 AM
* @param cls 类位置
* @return URL 返回值
*/
private URL getClassLocationURL(final Class cls) throws Exception{
if (cls == null) {
throw new IllegalArgumentException("class that input is null");
}
URL result = null;
final String clsAsResource = cls.getName().replace('.', '/')
.concat(".class");

final ProtectionDomain pd = cls.getProtectionDomain();

if (pd != null) {
final CodeSource cs = pd.getCodeSource();
if (cs != null) {
result = cs.getLocation();

}
}

if (result == null) {
final ClassLoader clsLoader = cls.getClassLoader();
result = clsLoader != null ? clsLoader.getResource(clsAsResource)
: ClassLoader.getSystemResource(clsAsResource);
}
return result;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值