spring boot 读取resources目录下文件的几种方式

发布于:2024-04-19 ⋅ 阅读:(156) ⋅ 点赞:(0)

1.使用注解

import org.springframework.beans.factory.annotation.Value;
import cn.hutool.core.io.IoUtil;
import org.springframework.core.io.Resource;

@Value("classpath:city.json")
Resource resource;

@PostConstruct
public void init() {
    // 转String
    String cityJson = IoUtil.readUtf8(resource.getInputStream());
    
    // 转List<String>
    List<String> list = IoUtil.readUtf8Lines(resource.getInputStream(), new ArrayList<>());
}

2.使用ResourceLoader接口

import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
@Component
public class YourComponent {
    private final ResourceLoader resourceLoader;
    public YourComponent(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }
    public void getResource() throws IOException {
        Resource resource = resourceLoader.getResource("classpath:your-file.txt");
        InputStream inputStream = resource.getInputStream();
        // 对文件进行操作,比如读取内容等
    }
}

3.使用ClassPathResource类

import org.springframework.core.io.ClassPathResource;

public void getResource() throws IOException {
    ClassPathResource resource = new ClassPathResource("your-file.txt");
    InputStream inputStream = resource.getInputStream();
    // 对文件进行操作,比如读取内容等
}

4.使用ResourceUtils.getFile()方法

注意这种方式在jar包里无法使用

import org.springframework.util.ResourceUtils;
import cn.hutool.core.io.FileUtil;

public void getResource() throws IOException {
    File file = ResourceUtils.getFile("classpath:your-file.txt");
    // 对文件进行操作,比如读取内容等
    // 读取文件内容到集合
    List<String> list= FileUtil.readUtf8Lines(todayFile);
}

参考文档:
springboot类路径下excel、word文件下载为空和打不开记录


网站公告

今日签到

点亮在社区的每一天
去签到