springboot上传文件到resources_Spring Boot读取resources目录文件方法详解

本文详细介绍了在Spring Boot中如何读取resources目录下的文件,提供了ClassPathResource和getContextClassLoader两种方法,并给出具体示例代码。通过这些方法,开发者可以在不同环境下读取如配置文件、模板文件等资源。
摘要由CSDN通过智能技术生成

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

}

}

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

时间: 2020-01-18

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值