如题,碰到了问题.

事情是这样的. 一个导入模板, 因为比较少, 所以就直接放在后台的resources中了.调试的时候是下载没有问题的.

等到发布后,下载就出问题了.

参照:


***.jar!\BOOT-INF\classes!\***.xml没有此文件
https://blog.csdn.net/weixin_43229107/article/details/85318551
通过 this.getClass().getResourceAsStream("/jdbcType.xml");


java工程内部文件路径读取问题jar:file:\No such file or directory
https://blog.csdn.net/ccmedu/article/details/78783248
URL classPath = Thread.currentThread().getContextClassLoader().getResource("xxxxx");


还有直接注入Resource的
@Value("classpath:thermopylae.txt")
private Resource res;
http://zetcode.com/articles/springbootloadres/


还有使用ResourceLoader来做的
@Autowired
private ResourceLoader resourceLoader;


Resource resource = resourceLoader.getResource("classpath:GeoLite2-Country.mmdb");


https://smarterco.de/java-load-file-from-classpath-in-spring-boot/
http://zetcode.com/articles/springbootloadres/
https://howtodoinjava.com/spring-core/how-to-load-external-resources-files-into-spring-context/

 

其实问题的关键在, jar中的文件访问不能使用resource.getFile, 而必须使用getInputStream.

访问磁盘可以用前者, 而访问jar内文件, 必须使用getInputStream().

不管是通过getClass().getxxx还是使用classLoader的getXXX也好, 都是要使用getInputStream这种.

另外发现一个问题点: 以前把文件读进来, 然后要写入outputStream, 使用了

byte[] data = new byte[fis.available()];

fis.available()这个东西给坏了事情. 
try (BufferedInputStream fis = new BufferedInputStream(res.getInputStream())) {

                int offset = 0;
int bytesRead = 0;
byte[] data = new byte[fis.available()];
while ((bytesRead = fis.read(data, offset, data.length - offset))
!= -1) {
offset += bytesRead;
if (offset >= data.length) {
break;
}
}
//String str = new String(data, 0, offset, "UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=" + res.getFilename());
response.setHeader("Access-Control-Allow-Origin", "*");
//response.setContentType("application/vnd.ms-read; charset=utf-8");
response.setContentType("application/octet-stream");
try (OutputStream outStream = new BufferedOutputStream(response.getOutputStream())) {
outStream.write(data);
outStream.flush();
}
}
看了一下JDK里inputstream的注释
    /**
* Returns an estimate of the number of bytes that can be read (or
* skipped over) from this input stream without blocking by the next
* invocation of a method for this input stream. The next invocation
* might be the same thread or another thread. A single read or skip of this
* many bytes will not block, but may read or skip fewer bytes.
*
* <p> Note that while some implementations of {@code InputStream} will return
* the total number of bytes in the stream, many will not. It is
* never correct to use the return value of this method to allocate
* a buffer intended to hold all data in this stream.
*
* <p> A subclass' implementation of this method may choose to throw an
* {@link IOException} if this input stream has been closed by
* invoking the {@link #close()} method.
*
* <p> The {@code available} method for class {@code InputStream} always
* returns {@code 0}.
*
* <p> This method should be overridden by subclasses.
*
* @return an estimate of the number of bytes that can be read (or skipped
* over) from this input stream without blocking or {@code 0} when
* it reaches the end of the input stream.
* @exception IOException if an I/O error occurs.
*/
public int available() throws IOException {
return 0;
}

里面有颜色的字, 意思大致是, 有人的实现会放进一个total number of bytes, 但很多不是....

看来JDK作者对大家的各种实现还是做了很多调查的...比较无奈, 大家都没有统一步调实现, (有人偷懒了,但是很有名,不能说, 推测, 所以含蓄地指出来)

这次我的这个文件比较小, 所以也就不用buffer, 直接暴力, 把inputstream转到byte array, 写入outputstream中.多么简单地代码!

最后代码就这么简单

            Resource res = new ClassPathResource(xxxxxxxxx, this.getClass());
logger.info(res.getURL().toString());
try (InputStream fis = res.getInputStream()) {
logger.info("available_length:" + fis.available());
byte[] data = IOUtils.toByteArray(fis);
logger.info("data_length:" + data.length);
response.setHeader("Content-Disposition", "attachment; filename=" + res.getFilename());
response.setHeader("Access-Control-Allow-Origin", "*");
response.setContentType("application/octet-stream");
try (OutputStream outStream = new BufferedOutputStream(response.getOutputStream())) {
outStream.write(data);
outStream.flush();
}
}
IOUtils.toByteArray(fis) 是apache common的方法.
解决! 这次, 在解决的过程中了解到了多种取Resource的方法, 我这里用的是class 的newClassPathResource("xxxxx",this.getClass())
这里的classPath默认是相对this.getClass的路径.如果需要绝对路径, 就需要加个/, 代表从根开始找. 另外,还参考了MyBatis加载Mapper.xml的过程, 使用的加载方式很独特, 特意用了一把, 挺不错!
大致是这样写的, 看样子很不错, 因为用的是 classpath*:, 瞬间好像高大上了, 和mybatis作者平起平坐了~~~~
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources("classpath*:abc/sadfsa/ssss.xxx");
Resource res = resources[0];

读了一下PathMatchingResourcePatternResolver相关的源代码, 感觉不错~~~,以后有时间在深究一下.

												

Springboot读取Jar文件中的resource的更多相关文章

  1. 解决springboot读取jar包中文件的问题

    转载自: https://www.oschina.net/question/2272552_2269641 https://stackoverflow.com/questions/25869428/c ...

  2. [Java] 在 jar 文件中读取 resources 目录下的文件

    注意两点: 1. 将资源目录添加到 build path,确保该目录下的文件被拷贝到 jar 文件中. 2. jar 内部的东西,可以当作 stream 来读取,但不应该当作 file 来读取. 例子 ...

  3. Jar中的Java程序如何读取Jar包中的资源文件

    Jar中的Java程序如何读取Jar包中的资源文件 比如项目的组织结构如下(以idea中的项目为例): |-ProjectName |-.idea/  //这个目录是idea中项目的属性文件夹 |-s ...

  4. 读取Jar包中的资源问题探究

    最近在写一个可执行jar的程序,程序中包含了2个资源包,一个是images,一个是files.问题来了,在Eclipse里开发的时候,当用File类来获取files下面的文件时,没有任何问题.但是当程 ...

  5. Java中读取txt文件中中文字符时,出现乱码的解决办法

    这是我写的一个Java课程作业时,遇到的问题. 问题描述: 我要实现的就是将txt文件中的内容按一定格式读取出来后,存放在相应的数组. 我刚开始运行时发现,英文可以实现,但是中文字符就是各种乱码. 最 ...

  6. SpringMVC 实现POI读取Excle文件中数据导入数据库(上传)、导出数据库中数据到Excle文件中(下载)

    读取Excale表返回一个集合: package com.shiliu.game.utils; import java.io.File; import java.io.FileInputStream; ...

  7. Android项目实战(二十四):项目包成jar文件,并且将工程中引用的jar一起打入新的jar文件中

    前言: 关于.jar文件: 平时我们Android项目开发中经常会用到第三方的.jar文件. 其实.jar文件就是一个类似.zip文件的压缩包,里面包含了一些源代码,注意的是.jar不包含资源文件(r ...

  8. 读取Excel文件中的单元格的内容和颜色

    怎样读取Excel文件中的单元格的内容和颜色 先创建一个Excel文件,在A1和A2中随意输入内容,设置A1的字体颜色为红色,A2的背景为黄色.需要 using Excel = Microsoft.O ...

  9. java 中读取本地文件中字符

    java读取txt文件内容.可以作如下理解: 首先获得一个文件句柄.File file = new File(); file即为文件句柄.两人之间连通电话网络了.接下来可以开始打电话了. 通过这条线路 ...

随机推荐

  1. Asp.Net Core 轻松学-一行代码搞定文件上传

    前言     在 Web 应用程序开发过程中,总是无法避免涉及到文件上传,这次我们来聊一聊怎么去实现一个简单方便可复用文件上传功能:通过创建自定义绑定模型来实现文件上传. 1. 实现自定义绑定模型 1 ...

  2. word中如何只修改英文的颜色

    替换->更多->使用通配符,查找[a-zA-Z],替换为^&,字体选红色

  3. 数据结构系列(2)之 AVL 树

    本文将主要讲解平衡二叉树中的 AVL 树,其中将重点讲解二叉树的重平衡方法,即左旋和右旋,以及 3+4 重构:这些方法都是后面要讲的 B 树,红黑树等 BBST 的重要基础:此外在看本文之前最好先看一 ...

  4. Shell编程(week4_day4)--技术流ken

    本节内容 1. shell函数 2. shell正则表达式 shell函数 shell中允许将一组命令集合或语句形成一段可用代码,这些代码块称为shell函数.给这段代码起个名字称为函数名,后续可以直 ...

  5. Springboot 系列(八)动态Banner与图片转字符图案的手动实现

    使用过 Springboot 的对上面这个图案肯定不会陌生,Springboot 启动的同时会打印上面的图案,并带有版本号.查看官方文档可以找到关于 banner 的描述 The banner tha ...

  6. 2017-2018年Scrum状态调查报告

    HOW SCRUM IS USED 在2017年的报告中,Scrum的应用范围在扩大,已经从其发源的IT部门扩展到了相距甚远的业务部门.2017-2018年度报告的其中一个主要目标就是关注更广泛的敏捷 ...

  7. 观察者模式 Observer 发布订阅模式 源 监听 行为型 设计模式(二十三)

    观察者模式 Observer 意图 定义对象一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖他的对象都得到通知并自动更新. 别名:依赖(Dependents),发布订阅(Publish-Su ...

  8. Oracle 常用Sql 语句

    Oracle数据库常常被用作项目开发的数据库之一:有时隔段时间没使用就会忘记一些常用的sql语法,所以我们有必要记录下常用的sql 语句,当我们需要时可以快速找到并运用. 1 创建表空间.创建用户及授 ...

  9. 读书笔记之_Win10 与Jmeter5.1.1界面兼容:

    读书笔记之win10 与jmeter5.1.1界面兼容:   调整前:

  10. APICloud Studio2新建应用报错和检出错误

    今天心血来潮,闲暇时间想做个移动应用app,听一哥们说APICloud开发app很方便,就查询了一下,看了之后简直就是热血沸腾,我感觉正是我一直要找的工具 信心满满的开始着手使用,看了一下介绍我选择了 ...