欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

Spring Boot读取resources目录文件方法详解

时间:2021-02-15 10:21:32|栏目:JAVA代码|点击:

这篇文章主要介绍了Spring Boot读取resources目录文件方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

在Java编码过程中,我们常常希望读取项目内的配置文件,按照Maven的习惯,这些文件一般放在项目的src/main/resources下,因此,合同协议PDF模板、Excel格式的统计报表等模板的存放位置是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();
    }
 
  }

上一篇:Java8 LocalDateTime极简时间日期操作小结

栏    目:JAVA代码

下一篇:java LRU(Least Recently Used )详解及实例代码

本文标题:Spring Boot读取resources目录文件方法详解

本文地址:http://www.codeinn.net/misctech/63418.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有