Java开发中关于资源路径获取问题

描述

在开发中经常会读取配置文件,在Web开发中大多数都是在项目路径下。核心的API类或者是Controller异或是jsp页面等,基本都是基于web应用的相对路径,很少去操作绝对路径,但是在客户端、jar启动方式、exe方式情况下,获取资源文件的路径就会是一个相对不同的问题。

最近公司有个开发需求,非网络的pc客户端处理需求。很多操作都可以收集、编辑放到配置文件去批处理执行,这时候遇到一个问题,就是在打jar包的时候,发现有个诡异的区别。

代码:

点击查看代码

- [JarPropertiesTest main = new JarPropertiesTest();
    String root = main.getClass().getResource("/").getPath();//第二次尝试获取路径方法
    System.out.println(System.getProperty("user.dir"));
    System.out.println("root:" + root);
    System.out.println(main.getClass().getProtectionDomain().getCodeSource().getLocation()
        .getFile());
    String jarpath = main.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();//第一次获取路径方法
    System.out.println(jarpath);
    jarpath = jarpath.indexOf(".jar") > -1 ? root : jarpath;//第三次为了兼容几种不同结果
    // if (jarpath.indexOf(".jar") > -1) jarpath = jarpath.substring(0, jarpath.lastIndexOf("/") +
    // 1);
    jarpath = jarpath + "configs/config.ini";
    Properties properties = new Properties();
    try {
      properties.load(new FileInputStream(jarpath));
      System.out.println(properties.get("params"));
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } ]

情况描述:

打包方法:Eclipse自带的Export和Ant

Eclipse中打包时,下面代码是生效的,可以直接拿到jar包存放的路径,然后configs目录与jar文件同级,则可以正常执行

采用main.getClass().getProtectionDomain().getCodeSource().getLocation().getPath()

用ant打包时候,采用main.getClass().getProtectionDomain().getCodeSource().getLocation().getPath()方法得到的路径则是jar路径且带jar文件名,是个全路径,需要自己手工去掉多余内容

Eclipse打包时main.getClass().getResource("/").getPath()得到是一个空字符串
ant打包时main.getClass().getResource("/").getPath()得到的是正确路径
如下图:

下面代码用ant打包时候可以正常获取到jar的存放路径,进而可以构建同级目录configs下文件路径
String filePath = System.getProperty("user.dir") + "/configs/config.ini";

总结

对于jar或者exe情况下自动获取相对路径下的文件情况,既要考虑操作系统环境又要考虑打包方式,所以要对根路径进行适配,也就是

String filePath = System.getProperty("user.dir") + "/configs/config.ini";
String root = main.getClass().getResource("/").getPath();
String jarpath = main.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();

都要获取,并进行判断,最终得到准确的根路径。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值