当前位置: 首页 > news >正文

读取Jar包下文件资源的问题及解决方案

问题

项目A代码调用到Resouces下的文件a.sh,打包成Jar包后,项目B调用对应方法时,出现报错,找不到a.sh文件路径,原来的代码可能是:

URL resource = getClass().getClassLoader().getResource("a.sh");
String path = resource.getPath();
System.out.println(path);

这样项目B是读取不到文件的。

解决方案

通过stream流获取文件,创建临时文件,记得处理异常以及临时文件执行结束后删除。

 // 使用 ClassLoader 获取资源文件的 InputStreamInputStream inputStream = this.class.getClassLoader().getResourceAsStream("a.sh");if (inputStream == null) {throw new IOException("The script file was not found in the resources directory.");}// 创建临时文件File tempScript = Files.createTempFile("tempScript", ".sh").toFile();tempScript.setExecutable(true);// 将资源文件内容写入临时文件try (FileOutputStream outputStream = new FileOutputStream(tempScript)) {byte[] buffer = new byte[1024];int bytesRead;while ((bytesRead = inputStream.read(buffer)) != -1) {outputStream.write(buffer, 0, bytesRead);}}
http://www.lryc.cn/news/379118.html

相关文章:

  • C++ 反转一个二进制串
  • 黑神话悟空-吉吉国王版本【抢先版】
  • 【尚庭公寓SpringBoot + Vue 项目实战】预约看房与租约管理(完结)
  • java拼图小游戏项目
  • [C++][数据结构][跳表]详细讲解
  • tinyxml
  • Docker(三)-Docker常用命令
  • [MRCTF2020]PixelShooter
  • vue实现的商品列表网页
  • 【泛微系统】e-cology非标配功能概览
  • Python基础教程(二十八):pip模块
  • 通信系统概述
  • http发展史(http0.9、http1.0、http1.1、http/2、http/3)详解
  • Hadoop 面试题(四)
  • 绽放光彩的小程序 UI 风格
  • 电脑文件夹怎么加密?文件夹加密的5种方法
  • 异步复位同步释放
  • JupyterLab使用指南(七):JupyterLab使用 LaTeX 生成数学公式
  • docker 环境部署
  • Spring中的ContextPath总结
  • C++设计模式——Composite组合模式
  • Android提供的LruCache类简介(1)
  • 【分布式系列】分布式锁timeout了怎么办?
  • System.getProperty()方法总结
  • 大型语言模型在AMD GPU上的推理优化
  • Apple - Core Foundation Design Concepts
  • lua中的lfs库介绍
  • PyCharm 快捷键积累
  • C++进阶之AVL树
  • sizeof 和 strlen 比较