Spring Boot中如何读取resources目录下的文件
生活随笔
收集整理的這篇文章主要介紹了
Spring Boot中如何读取resources目录下的文件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在Java編碼過程中,我們常常希望讀取項目內的配置文件,按照Maven的習慣,這些文件一般放在項目的src/main/resources下。因此,我們把合同的PDF模板存放于resources/template/test.pdf,以作測試用例,下面提供兩種讀取方式,它們分別在windows和Linux環境(linux下jar包)都可以正常運行。
方法一ClassPathResource
String pdfFilePath = "template/test.pdf"; Resource resource = new ClassPathResource(pdfFilePath);
通過如下方法可以轉Resource換成InputStream :
InputStream is = resource.getInputStream();
方法二getContextClassLoader
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(pdfFilePath);
測試用例
public static void main(String[] args) {
try {
String pdfFilePath = "template/test.pdf";
Resource resource = new ClassPathResource(pdfFilePath);
System.out.println( resource.getURI() + " -- ****** path = ");
if (resource.isReadable()) {
//每次都會打開一個新的流
InputStream is = resource.getInputStream();
System.out.println("方法一 " + is.available());
}
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(pdfFilePath);
System.out.println("方法二 " + inputStream.available());
} catch (IOException e) {
e.printStackTrace();
}
}
如果有其它讀取的辦法,歡迎留言。
總結
以上是生活随笔為你收集整理的Spring Boot中如何读取resources目录下的文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 八百元八核的服务器?二手服务器(工作站)
- 下一篇: SIM卡信息的管理