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

本文探讨了SpringBoot项目中如何在本地与线上环境切换时,正确处理资源目录下JSON文件的访问问题。通过对比ClassLoader.getResource()与ClassPathResource,作者展示了在部署到线上时如何使用ClassPathResource类来获取并读取文件,以避免路径解析问题。
摘要由CSDN通过智能技术生成

        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读取资源路径下的文件,可以直接获取到一个输入流,然后对流进行操作即可。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值