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() {
? ? // 轉(zhuǎn)String
? ? String cityJson = IoUtil.readUtf8(resource.getInputStream());
? ? // 轉(zhuǎn)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();
? ? ? ? // 對文件進行操作睁蕾,比如讀取內(nèi)容等
? ? }
}
3.使用ClassPathResource類
import org.springframework.core.io.ClassPathResource;
public void getResource() throws IOException {
? ? ClassPathResource resource = new ClassPathResource("your-file.txt");
? ? InputStream inputStream = resource.getInputStream();
? ? // 對文件進行操作唧垦,比如讀取內(nèi)容等
}
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");
? ? // 對文件進行操作疲憋,比如讀取內(nèi)容等
? ? // 讀取文件內(nèi)容到集合
? ? List<String> list= FileUtil.readUtf8Lines(todayFile);
}