当前位置: 移动技术网 > IT编程>开发语言>Java > Spring Boot读取resources目录文件方法详解

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

2020年03月09日  | 移动技术网IT编程  | 我要评论

这篇文章主要介绍了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();
    }
 
  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网