How to read resources catalog files by SpringBoot
This article mainly explains the "SpringBoot how to read resources directory files", the article explains the content is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "SpringBoot how to read resources directory files" bar!
In the Java coding process, we often want to read the configuration files within the project, according to Maven custom, these files are generally placed under the project src/main/resources, therefore, the contract agreement PDF template, Excel format statistical reports and other templates are stored in resources/template/test.pdf, the following provides two read methods, they are in windows and Linux environment (linux jar package) can run normally.
Method one: ClassPathResource
String pdfFilePath = "template/test.pdf"; Resource resource = new ClassPathResource (pdfFilePath)
You can convert Resource to InputStream by using the following methods:
InputStream is = resource.getInputStream ()
Method 2 getContextClassLoader
InputStream inputStream = Thread.currentThread () .getContextClassLoader () .getResourceAsStream (pdfFilePath)
Test case
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 ()) {/ / opens a new stream InputStream is = resource.getInputStream () every time; System.out.println (method one + is.available ()) } InputStream inputStream = Thread.currentThread (). GetContextClassLoader (). GetResourceAsStream (pdfFilePath); System.out.println ("method II" + inputStream.available ());} catch (IOException e) {e.printStackTrace ();}}
Thank you for your reading, the above is the content of "SpringBoot how to read resources directory files". After the study of this article, I believe you have a deeper understanding of how SpringBoot reads resources directory files, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!