美文网首页
[BUG排查]class path resource [xxx]

[BUG排查]class path resource [xxx]

作者: AbstractCulture | 来源:发表于2021-09-06 18:04 被阅读0次

背景

之前做了一个读取resource目录下的文件,解析脚本并缓存起来的功能。但是,在项目部署的过程中,直接报错:
<p style="color:red">class path resource [xxx] cannot be resolved to absolute file path because it does not reside in the file system:</p>
What the fuck?
于是有了今天这篇文章.

产生的原因

通过编译器打成的jar,不能采用这种直接读取路径的方式去操作文件。
另一种解释

解决方案

ClassPathResource

package com.example.example;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import javax.annotation.PostConstruct;
import java.io.*;

/**
 * com.example.example
 *
 * @author jaymin
 * @since 2021/9/6
 */
@Component
@Slf4j
public class LoadingFile {

    /**
     * 读取helloworld.txt
     */
    @PostConstruct
    public void loadingFile() throws IOException {
        Resource resource = new ClassPathResource("helloworld.txt");
        InputStream inputStream = resource.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        try (BufferedReader bufferedReader = new BufferedReader(inputStreamReader);) {
            String content = bufferedReader.readLine();
            log.info("内容:" + content);
        } catch (IOException e) {
            log.error("读取helloworld文件失败:" + e);
        }

    }

}
文件
  • 打包验证
maven
  • 启动jar
result

相关文章

网友评论

      本文标题:[BUG排查]class path resource [xxx]

      本文链接:https://www.haomeiwen.com/subject/qpcywltx.html