在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(); } }
如果有其它讀取的辦法,歡迎留言。