Detailed explanation of the method of reading resources directory file by spring boot

This article mainly introduces the detailed method of reading resources directory files by spring boot. It is introduced in great detail through the example code, which has a certain reference value for everyone's study or work. Friends in need can refer to it

In the process of java coding, we often want to read the configuration files in the project. According to Maven's habit, these files are generally placed under Src / main / resources of the project. Therefore, the storage location of contract agreement PDF template, excel statistical report and other templates is resources / template / test Pdf, the following two reading methods are provided, which can run normally in windows and Linux environment (jar package under Linux).

Method 1: classpathresource

String pdfFilePath = "template/test.pdf";
Resource resource = new ClassPathResource(pdfFilePath);

You can convert a resource to an InputStream by the following method:

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()) {
        //每次都会打开一个新的流
        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();
    }

  }

The above is the whole content of this article. I hope it will help you in your study, and I hope you will support us a lot.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>