栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot加载 Resource 文件 SpringBoot 加载 获取 Resource 文件 springboot 加载 获取 resource 下 资源 文件

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot加载 Resource 文件 SpringBoot 加载 获取 Resource 文件 springboot 加载 获取 resource 下 资源 文件

不同Spring版本 方式不一样

第一种
 String path = this.getClass().getClassLoader().getResource("").getPath() .concat("files/a.txt"); 
 path = URLDecoder.decode(path); 
 File file = new File(path);
第二种
ClassPathResource classPathResource = new ClassPathResource("files/a.txt");
File file = classPathResource.getFile(); // 获取文件对象
第三种, 最有效

前面两种大多数情况 打包成jar运行 都是获取不到文件,war好像可以

jar 方式获取文件方式:

  1. 先获取 inputStream
  2. 然后在把 inputStream流 输出到硬盘文件
  3. 在获取这个硬盘文件

FileUtils 使用 org.apache.commons.io.FileUtils
需要加入 commons.io maven依赖或者 jar包


    commons-io
    commons-io
    2.6

示例

// 获取输入流
Resource classPathResource = new ClassPathResource("/excel-templates/excel-dict-customs.xlsx");
InputStream inputStream = classPathResource.getInputStream();

String outFilePath = ( new File(".")).getCanonicalPath().concat(String.format("/tmp-file-%s", System.currentTimeMillis())); 
// 将 InputStream 复制输出到 指定文件上
File file = new File(outFilePath);
FileUtils.copyInputStreamToFile(inputStream, file);
// 关闭输入流
inputStream.close();
System.out.printf("文件是否存在: %s%n", file.exists());


操作完 File 记得删除文件

暑期编程PK赛 得CSDN机械键盘等精美礼品!
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1016493.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号