zoukankan      html  css  js  c++  java
  • 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();
            }
     
        }

           如果有其它读取的办法,欢迎留言。

  • 相关阅读:
    pythonday06数据类型(四)
    pythonday05数据类型(三)
    pythonday04数据类型(二)
    pythonday03数据类型(一)
    Apollo自动驾驶实践——第0讲:导论
    图论学习:生成树的Matrix-tree定理
    2020杭电多校6 Expectation
    2020牛客暑期多校第九场 B Groundhog and Apple Tree
    图论:二分图最大权匹配KM算法
    第十章 百度Apollo实战
  • 原文地址:https://www.cnblogs.com/east7/p/12208114.html
Copyright © 2011-2022 走看看