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

资源文件获取时找不到文件

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

资源文件获取时找不到文件

        springboot项目需要获取资源目录下的json文件,本地使用getClassLoader().getResource()获取可以,但是部署到线上后,获取到文件路径是file:/tmp/sop.jar!/BOOT-INF/classes!/ueditor-config.json,解决方案使用ClassPathResource类

getClassLoader().getResource()
private String configPath = this.getClass().getClassLoader().getResource("ueditor-config.json").getPath();

// configPath = /E:/Development/xxx/target/classes/ueditor-config.json

StringBuilder builder = new StringBuilder();
try {
    InputStreamReader reader = new InputStreamReader(new FileInputStream(configPath), "UTF-8");
    BufferedReader bfReader = new BufferedReader(reader);
    String tmpContent = null;
    while ((tmpContent = bfReader.readLine()) != null) {
        builder.append(tmpContent);
    }
    bfReader.close();
} catch (UnsupportedEncodingException e) {
    // 忽略
}
  1. idea 本地运行时,configPath = /E:/Development/xxx/target/classes/ueditor-config.json
  2. 部署到线上运行,configPath = file:/tmp/sop.jar!/BOOT-INF/classes!/ueditor-config.json
  3. 线上不能使用该方式
原因

        Java项目部署到线上时,会将项目打包成一个jar包,jar包是一个文件,而不是文件夹,因此通过/tmp/sop.jar!/BOOT-INF/classes!/ueditor-config.json无法定位到文件。

ClassPathResource类
Resource resource = new ClassPathResource(configPath);
InputStream is = resource.getInputStream();

StringBuilder builder = new StringBuilder();
try {
    InputStreamReader reader = new InputStreamReader(is, "UTF-8");
    BufferedReader bfReader = new BufferedReader(reader);
    String tmpContent = null;
    while ((tmpContent = bfReader.readLine()) != null) {
        builder.append(tmpContent);
    }
    bfReader.close();
} catch (UnsupportedEncodingException e) {
    // 忽略
}

        通过 ClassPathResource读取资源路径下的文件,可以直接获取到一个输入流,然后对流进行操作即可。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/991813.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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