maven 模块化工程 跨模块读取项目资源文件,获得资源文件真实路径

maven 多模块工程 跨模块读取资源文件

1.最简单的方式,就是直接在资源文件目录读取,但是这种方式,打成jar包后会读取失败,因为资源文件在jar包内,是不能通过绝对路径访问的

String pfxPath = YSTxService.class.getResource("/cert/"+YinShengConstant.partnerId+".pfx").getPath().toString();
String cerPath = YSTxService.class.getResource("/cert/businessgate.cer").getPath().toString();

2.使用流的方式直接读取文件内容,这种方式对于需要传绝对路径或File对象做为参数也是不可以的

InputStream stream = getClass().getClassLoader().getResourceAsStream("/cert/"+YinShengConstant.partnerId+".pfx");
InputStream stream = getClass().getClassLoader().getResourceAsStream("/cert/businessgate.cer");

3.如果需要使用资源文件的绝对路径或File对象,则可以使用流,将资源文件复制到jar包外,在用绝对路径或者File对象使用

File partnerId = new File("YScert/"+YinShengConstant.partnerId+".pfx");
File businessgate = new File("YScert/businessgate.cer");

try {
      if (!partnerId.exists()) {
            //第一种方式
                InputStream stream = YSTxService.class.getResourceAsStream("/cert/"+YinShengConstant.partnerId+".pfx");
                //第二种方式
                InputStream stream0 = getClass().getClassLoader().getResourceAsStream("cert/"+YinShengConstant.partnerId+".pfx");
           FileUtils.copyInputStreamToFile(stream, partnerId);
      }
      if (!businessgate.exists()) {
            InputStream stream = getClass().getClassLoader().getResourceAsStream("/cert/businessgate.cer");
            FileUtils.copyInputStreamToFile(stream, businessgate);
      }
      } catch (IOException e) {
         log.error(e.getMessage());
         throw new YshopException(e.getMessage());
      }


String absolutePath = partnerId.getAbsolutePath();
String absolutePath1 = businessgate.getAbsolutePath();

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值