SpringBoot项目构建成jar运行后,如何正确读取resource下的文件

不管你使用的是SpringBoot 1.x还是SpringBoot2.x,在开Dev环境中使用eclipse、IEAD、STS等IDE工具,进行resource目录下文件的获取,简单的采用@Value注解的形式就可以得到,文件读取的主知一般情况下也是没有问题的,比如

File file = ResourceUtils.getFile("classpath:exceltmp/template_export.xls");

度娘检索出来的文章也基本上告诉你,这样是没有问题的。But,使用mvn package构建成jar文件,运行后报异常如下:

java.io.FileNotFoundException: class path resource [exceltmp/template_export.xls] cannot be resolved to absolute file path because it does not reside in the file system:jar:file:/Users/apple/project-code/xdod-project/xdod-backend/target/xdod-backend.jar!/BOOT-INF/classes!/exceltmp/template_export.xls

Resource下的文件是存在于jar这个文件里面,在磁盘上是没有真实路径存在的,它其实是位于jar内部的一个路径。所以通过ResourceUtils.getFile或者this.getClass().getResource("")方法无法正确获取文件。

有一种比较偷懒的做法:将文档放在项目外,应用可以读取到的一个固定目录。按正常的方式读取即可,但可维护性比较差,很容易被误操作丢失。

文本文件读取

这种情况下可以采用流的方式来读取文件,拿到文件流再进行相关的操作。如果你使用Spring框架的话,可以采用ClassPathResource来读取文件流,将文件读取成字符串才进行二次操作,比较适用于文本文件,如properties,txt,csv,SQL,json等,代码参考:

String data = "";
ClassPathResource cpr = new ClassPathResource("static/file.txt");
try {
byte[] bdata = FileCopyUtils.copyToByteArray(cpr.getInputStream());
data = new String(bdata, StandardCharsets.UTF_8);
} catch (IOException e) {
LOG.warn("IOException", e);
}

这里提供一个工具类来帮助大家读取文件:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.stream.Collectors; import org.springframework.core.io.ClassPathResource; public final class ClassPathResourceReader {
/**
* path:文件路径
* @since JDK 1.8
*/
private final String path; /**
* content:文件内容
* @since JDK 1.6
*/
private String content; public ClassPathResourceReader(String path) {
this.path = path;
} public String getContent() {
if (content == null) {
try {
ClassPathResource resource = new ClassPathResource(path);
BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
content = reader.lines().collect(Collectors.joining("\n"));
reader.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
return content;
}
}

使用方式也是相当简单

String content = new ClassPathResourceReader("log4j.properties").getContent();

非文本文件读取

更多的情况是读取非文本文件,比如xls,还是希望拿到一个文件,再去解析使用。参考代码如下:

ClassPathResource classPathResource = new ClassPathResource("exceltmp/template_export.xls"");

InputStream inputStream = classPathResource.getInputStream();
//生成目标文件
File somethingFile = File.createTempFile("template_export_copy", ".xls");
try {
FileUtils.copyInputStreamToFile(inputStream, somethingFile);
} finally {
IOUtils.closeQuietly(inputStream);
}

拿到目标文件后,再按照正常的取法如ResourceUtils.getFile,读取即可。

参考文章:https://stackoverflow.com/questions/25869428/classpath-resource-not-found-when-running-as-jar

获取更多内容请关注公众号

SpringBoot项目构建成jar运行后,如何正确读取resource下的文件的更多相关文章

  1. maven将自己的springboot项目打包成jar包后,作为工具包引入其他项目,找不到jar中的类

    将springboot项目打包成jar包,作为工具包导入项目后,找不到jar中的类. 原因是:springboot项目使用了自动的打包插件. 原先的插件配置: <build> <pl ...

  2. Springboot项目打包成jar运行2种方式

    最近公司有个项目需要移植到SpringBoot框架上,项目里面又有许多第三方jar包,在linux服务器上最方便的就是用jar的方式来运行SpringBoot项目了,因此我研究了2种打jar包的方式, ...

  3. Spring项目读取resource下的文件

    目录 一.前提条件 二.使用ClassPathResource类读取 2.1.Controller.service中使用ClassPathResource 2.2.单元测试使用ClassPathRes ...

  4. springboot读取resource下的文件

    public static String DEFAULT_CFGFILE = ConfigManager.class.getClassLoader().getResource("conf/s ...

  5. springboot 读取 resource 下的文件

    ClassPathResource classPathResource = new ClassPathResource("template/demo/200000168-check-resp ...

  6. SpringBoot项目打包成jar后,启动脚本

    将springboot项目打包成jar后,上传至服务器,每次都需要手敲命令,重新部署项目,可将这些命令写入脚本中,直接运行. 启动脚本(start.sh): CUR_PATH=$(cd "$ ...

  7. SpringBoot 项目打包后获取不到resource下资源的解决

    SpringBoot 项目打包后获取不到resource下资源的解决 在项目中有几个文件需要下载,然后不想暴露真实路径,又没有CDN,便决定使用接口的方式来获取文件.最初的时候使用了传统的方法来获取文 ...

  8. 用gradle把springboot项目打包成jar

    ``` 用gradle把springboot项目打包成jar ```### build.gradle 中添加 buildscript { repositories { mavenLocal() mav ...

  9. SpringBoot读取Resource下文件的几种方式(十五)

    需求:提供接口下载resources目录下的模板文件,(或者读取resources下的文件)给后续批量导入数据提供模板文件. 方式一:ClassPathResource //获取模板文件:注意此处需要 ...

随机推荐

  1. Web service的学习资源

    看了半天的Web service,总算是对它有了一点眉目,不枉此行:)那就整理一下吧,来日还需要用到呢! 1.什么是Web service(请看这儿). 2.Web service的开发        ...

  2. wpf 禁用window的systemmenu

    private IntPtr WidProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { if (m ...

  3. centos7 防火墙问题

    centos从7开始默认用的是firewalld,这个是基于iptables的,虽然有iptables的核心,但是iptables的服务是没安装的.所以你只要停止firewalld服务即可:sudo ...

  4. Qt SizePolicy 属性(每个控件都有一个合理的缺省sizePolicy。QWidget.size()默认返回值是(640, 480),QWidget.sizeHint()默认返回值是(-1, -1))

    控件的sizePolicy说明控件在布局管理中的缩放方式.Qt提供的控件都有一个合理的缺省sizePolicy,但是这个缺省值有时不能适合 所有的布局,开发人员经常需要改变窗体上的某些控件的sizeP ...

  5. Substring详解

    class Program { static void Main(string[] args) { string str = "Hello World!"; ; //Substri ...

  6. 微信小程序把玩(二十一)switch组件

    原文:微信小程序把玩(二十一)switch组件 switch开关组件使用主要属性: wxml <!--switch类型开关--> <view>switch类型开关</vi ...

  7. 零元学Expression Blend 4 - Chapter 9 用实例了解布局容器系列-「Canvas」

    原文:零元学Expression Blend 4 - Chapter 9 用实例了解布局容器系列-「Canvas」 本系列将教大家以实做案例认识Blend 4 的布局容器,此章介绍的布局容器是Blen ...

  8. 关于SetLocaleInfo()

    原文:关于SetLocaleInfo() 此函数用于设置系统的一些本地信息, 非常有用. 比如日期格式为'yyyy/mm/dd'时, 稍微不注意,有些程序语句会报错. 以下资料网络收集: 1. Set ...

  9. 核心思想:许多公司都没有认识到云储存的革命性(类似QQ把它搞成了用户的家、再也离不开了)

    在云储存刚刚兴起的时候,也就是dropbox刚刚进入大家视野的时候.许多人都是简单的认为这只是一个提供在线存储的服务而已,许多公司都没有认识到云储存的革命性. 对于这些大公司贸然进入一些新的领域是需要 ...

  10. QT+OpenGL读取显示图片,OpenGL在QT里的刷新问题(好几篇)

    GLuint readImage(char *filename){    GLuint tex_id;    GLint alignment; QImage tex, buf;    buf.load ...