赞
踩
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<>());
}
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();
// 对文件进行操作,比如读取内容等
}
}
import org.springframework.core.io.ClassPathResource;
public void getResource() throws IOException {
ClassPathResource resource = new ClassPathResource("your-file.txt");
InputStream inputStream = resource.getInputStream();
// 对文件进行操作,比如读取内容等
}
注意这种方式在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);
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。