jar包获取resource下配置文件路径

我们在代码里可以这样写

  String krb5Conf = this.class.getClassLoader().getResource("krb5.conf").getFile();

但是打成jar包后就不行了,我们有很多方法获取jar包路径或者resource下文件路径

   File path = new File(ResourceUtils.getURL("classpath:").getPath());
  if (!path.exists()) path = new File("");
log.error("1:{}", path.getAbsolutePath());

//第二种
log.error("2:{}", System.getProperty("user.dir"));

//第三种
String path1 = ClassUtils.getDefaultClassLoader().getResource("test.txt").getPath();
                log.error("3:{}",URLDecoder.decode(path1, "utf-8"));

//第四种
String path2 = ResourceUtils.getURL("classpath:test.txt").getPath();
log.error("4:{}",path2);
//第五种
ApplicationHome h = new ApplicationHome(Demo.class);
File jarF = h.getSource();
log.error("5:{}",jarF.getParentFile().toString());

但是打印后你会发现路径里面带 !,此时就算你去掉!也不行

String path = ClassUtils.getDefaultClassLoader().getResource("test.txt").getPath();

就算把路径copy到linux,用cat命令也显示文件不合法,猜测打包之后的jar就是无法获取的

但是我们可以读取文件,然后写入固定路径,再使用

            write(getStringByInputStream(this.class.getClassLoader().getResourceAsStream("test.txt")),"/data/test.txt");
public static String getStringByInputStream(InputStream inputStream) {
  BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
  try {
      StringBuilder result = new StringBuilder();
      String line;
      while ((line = bufferedReader.readLine()) != null) {
          result.append(line);
      }
      return result.toString();
  } catch (Exception e) {
      try {
          inputStream.close();
          bufferedReader.close();
      } catch (Exception e1) {
      }
  }
  return null;



blic static void write(String txt, String file) {
  try {
      BufferedWriter out = new BufferedWriter(new FileWriter(file));
      out.write(txt);
      out.close();
  } catch (IOException e) {
  }

当然了,生产环境中我们一般都是容器目录挂载,然后直接引用的

比如让运维吧文件a.txt放到机器中,然后容器data/挂载到该文件目录,我们就可以直接用/data/a.txt了

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

orange大数据技术探索者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值