Spring Boot中如何读取resources目录下文件呢?
下文笔者讲述SpringBoot读取Resources目录下文件的方法分享,如下所示
读取Resources目录下文件的实现思路
方式1:
使用ClassPathResource实例化即可读取resources目录下的文件
String path = "test/test.txt";
Resource resource = new ClassPathResource(path);
方式2:
使用Thread.currentThread().getContextClassLoader().getResourceAsStream(path)
读取Resource目录
例如:读取Resource目录下的 test目录下的test.txt文件
public static void main(String[] args) {
try {
String pdfFilePath = "test/test.txt";
Resource resource = new ClassPathResource(pdfFilePath);
System.out.println( resource.getURI() + " -- ****** path = ");
if (resource.isReadable()) {
//每次都会打开一个新的流
InputStream is = resource.getInputStream();
System.out.println("方式1: " + is.available());
}
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(pdfFilePath);
System.out.println("方式2:" + inputStream.available());
} catch (IOException e) {
e.printStackTrace();
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


