springboot读取文件打成jar包后访问不到怎么解决
springboot读取文件,打成jar包后访问不到最新开发出现一种情况,springboot打成jar包后读取不到文件,原因是打包之后,文件的虚拟路径是无效的,只能通过流去读取。文件在resources下publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");InputStreaminputStre
springboot读取文件,打成jar包后访问不到
最新开发出现一种情况,springboot打成jar包后读取不到文件,原因是打包之后,文件的虚拟路径是无效的,只能通过流去读取。
文件在resources下
public void test() {
List names = new ArrayList<>();
InputStreamReader read = null;
try {
ClassPathResource resource = new ClassPathResource("name.txt");
InputStream inputStream = resource.getInputStream();
read = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(read);
String txt = null;
while ((txt = bufferedReader.readLine()) != null) {
if (StringUtils.isNotBlank(txt)) {
names.add(txt);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (read != null) {
try {
read.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} springboot打jar包后台无法访问静态文件夹
1.ResourceUtils
平常我们写spring boot 项目的时候偶尔会在后台用到classpath 底下的文件,一般我们都是这样写的
File file = ResourceUtils.getFile("classpath:static/image/image");这样情况下本来是没啥问题的。但是用 打jar 包 运行以后就会找不到这个文件。
Resource下的文件是存在于jar这个文件里面,在磁盘上是没有真实路径存在的,它其实是位于jar内部的一个路径。所以通过ResourceUtils.getFile或者this.getClass().getResource("")方法无法正确获取文件。
对于这种情况。有时候会把项目文档放到项目外边,但是这样很容易把这些东西误删除掉。
2.ClassPathResource
ClassPathResource cpr = new ClassPathResource("static/image/image/kpg");
InputStream in = cpr.getInputStream();3. ResourceLoader
public class ResourceRenderer {
public static InputStream resourceLoader(String fileFullPath) throws IOException {
ResourceLoader resourceLoader = new DefaultResourceLoader();
return resourceLoader.getResource(fileFullPath).getInputStream();
}
}用法
InputStream in = ResourceRenderer.resourceLoader("classpath:static/image/image");这样就完美的解决了jar包底下路径无法访问的问题。
Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















