百木园-与人分享,
就是让自己快乐。

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();

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


来源:https://www.cnblogs.com/gr13811787801/p/16149525.html
本站部分图文来源于网络,如有侵权请联系删除。

未经允许不得转载:百木园 » Java开发中关于资源路径获取问题

相关推荐

  • 暂无文章