https://blog.csdn.net/fzy629442466/article/details/131835539?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522170225859316800197059584%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=170225859316800197059584&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~first_rank_ecpm_v1~rank_v31_ecpm-1-131835539-null-null.nonecase&utm_term=resources&spm=1018.2226.3001.4450
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);
}