java如何读取resources目录中的文件呢?
下文笔者讲述java代码读取resource目录中文件的方法及示例分享,如下所示
我们都知道SpringBoot打包生成jar文件后 resource目录中的文件会存储在class目录中 那么我们如何才能读取文件呢? 下文笔者将通过示例的方式一一道来,如下所示
文本文件读取
使用Spring框架
可使用ClassPathResource来读取文件流
将文件读取成字符串才进行二次操作
如:
properties,txt,csv,SQL,json等
例:
String data = "";
ClassPathResource cpr = new ClassPathResource("static/test.txt");
try {
byte[] bdata = FileCopyUtils.copyToByteArray(cpr.getInputStream());
data = new String(bdata, StandardCharsets.UTF_8);
} catch (IOException e) {
LOG.warn("IOException", e);
}
例:读取文件的工具类
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.stream.Collectors;
import org.springframework.core.io.ClassPathResource;
public final class ClassPathResourceReader {
/**
* path:文件路径
* @since JDK 1.8
*/
private final String path;
/**
* content:文件内容
* @since JDK 1.6
*/
private String content;
public ClassPathResourceReader(String path) {
this.path = path;
}
public String getContent() {
if (content == null) {
try {
ClassPathResource resource = new ClassPathResource(path);
BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
content = reader.lines().collect(Collectors.joining("\n"));
reader.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
return content;
}
}
//使用方法
String content = new ClassPathResourceReader("log4j.properties").getContent();
非文本文件读取
例:读取resource目录下的xls文件
我们可参考以下代码
例
ClassPathResource classPathResource = new ClassPathResource("test/template_export.xls"");
InputStream inputStream = classPathResource.getInputStream();
//生成目标文件
File somethingFile = File.createTempFile("template_export_copy", ".xls");
try {
FileUtils.copyInputStreamToFile(inputStream, somethingFile);
} finally {
IOUtils.closeQuietly(inputStream);
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


