springboot使用ResourcePatternUtils模糊查询resources路径下的文件(类似File.listFiles)

作者: ʘᴗʘ发布时间:2021-12-19 21:31 浏览量:285 点赞:238 售价:0

前言

在springboot中我们如果要读取resources文件夹下的文件,是不能使用java传统的File来读取的。本文向您介绍两种读取resources路径下文件的两种方式:

读取resources下单个文件

加入我们要读取resources/abc.css这个文件,可以通过ClassPathResource resource = new ClassPathResource(文件路径);来读取。代码如下:

ClassPathResource resource = new ClassPathResource(文件路径);
try (InputStream inputStream = resource.getInputStream()) {
    String result = new String(inputStream.readAllBytes());
} catch (IOException e) {
    logger.error("读取失败");
}

读取、查询resources下多个文件

有时候,我们需要读取resources路径下的多个文件:比如要读取该路径下的所有css文件;要读取某个子文件夹中的所有文件;类似这样的需求,因为无法使用java File的listFiles方法,所以很多同学不知道该怎么操作。其实可以使用ResourcePatternUtils工具类实现,该类是springboot提供的,专门用来批量查询、读取resources路径下的文件。

假如我们要读取resources/css/路径下的所有文件,代码如下:

package com.coderbbb.book1;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternUtils;

import java.io.IOException;
import java.io.InputStream;

@SpringBootApplication
public class Book1Application {

    public static void main(String[] args) throws Exception {


        ConfigurableApplicationContext applicationContext = SpringApplication.run(Book1Application.class, args);

        Resource[] resources = ResourcePatternUtils.getResourcePatternResolver(applicationContext).getResources("classpath:statics/css/**");
        for (Resource resource : resources) {
            try (InputStream inputStream = resource.getInputStream()) {
            
                String result = new String(inputStream.readAllBytes());
            
                System.out.println("文件" + resource.getFilename() + "的内容是:" + result);
            
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}

以上代码中getResources方法的入参通过*来实现模糊查询,单个*代表当前目录任意字符,多个*则代表多层目录模糊匹配。

版权声明:《springboot使用ResourcePatternUtils模糊查询resources路径下的文件(类似File.listFiles)》为CoderBBB作者「ʘᴗʘ」的原创文章,转载请附上原文出处链接及本声明。

原文链接:https://www.coderbbb.com/articles/58

其它推荐:

user

ʘᴗʘ

77
文章数
52518
浏览量
41924
获赞数
67.80
总收入