Open techiall opened 4 years ago
返回 iterator
@SneakyThrows
public static <T> Iterator<T> read(String resourceLocation, Function<String, T> mapper) {
ClassPathResource classPathResource = new ClassPathResource(resourceLocation);
byte[] read = FileCopyUtils.copyToByteArray(classPathResource.getInputStream());
return Arrays.stream(new String(read).split("\n")).map(mapper).iterator();
}
public class ResourceUtils {
private ResourceUtils() {
throw new IllegalStateException("Utility class");
}
@SneakyThrows
public static <T> List<T> fileRead(String resourceLocation, Function<String, T> mapper) {
if (resourceLocation == null) {
return Collections.emptyList();
}
if (-1 != resourceLocation.compareToIgnoreCase("classpath:")) {
resourceLocation = resourceLocation.replaceAll("(?i)classpath:", "");
}
ClassPathResource classPathResource = new ClassPathResource(resourceLocation);
byte[] read = FileCopyUtils.copyToByteArray(classPathResource.getInputStream());
return Arrays.stream(new String(read).split("\n"))
.map(mapper).collect(Collectors.toList());
}
resources
文件夹内容如下,假如要读取user.txt
里面的文本,并按行输出。user.txt
内容为。可以使用
org.springframework.core.io.ClassPathResource
并配合FileCopyUtils
,demo 如下:输出结果为:
当然了你也可以读取 resource 里面的其他文件,如
application.yml
,一样是可以读取成功的。other
很多人在开发的时候可以正常读取
resource
文件夹里面的文件,但是打包发布到线上,就报错。很大原因是使用了诸如
File
/Files
/Paths
之类的方法。(毕竟
ClassPathResource
里面有getURI()
/getPath()
/getFile()
,然后再去读取,然后你会发现这么读取都是失败的。