Spring Boot中如何读取resources目录下文件呢?

乔欣 SpringBoot 发布时间:2023-02-17 17:48:26 阅读数:8368 1
下文笔者讲述SpringBoot读取Resources目录下文件的方法分享,如下所示

读取Resources目录下文件的实现思路

方式1:
   使用ClassPathResource实例化即可读取resources目录下的文件
    String path = "test/test.txt";
     Resource resource = new ClassPathResource(path);

方式2:
   使用Thread.currentThread().getContextClassLoader().getResourceAsStream(path)
    读取Resource目录
例如:读取Resource目录下的 test目录下的test.txt文件
 public static void main(String[] args) {
	try {
		String pdfFilePath = "test/test.txt";
		Resource resource = new ClassPathResource(pdfFilePath);
		System.out.println( resource.getURI() + " -- ****** path = ");

		if (resource.isReadable()) {
			//每次都会打开一个新的流
			InputStream is = resource.getInputStream();
			System.out.println("方式1: " + is.available());
		}
		InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(pdfFilePath);
		System.out.println("方式2:" + inputStream.available());
	} catch (IOException e) {
		e.printStackTrace();
	}
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaFramework/SpringBoot/202302/5832.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者