您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在SpringBoot 2.0.1.RELEASE应用中读取文件

在SpringBoot 2.0.1.RELEASE应用中读取文件

我发现,结合使用ResourceLoaderResourcePatternUtils这是在Spring Boot应用程序中从类路径资源文件夹列出/读取文件的最佳方法

@RestController
public class ExampleController {

    private ResourceLoader resourceLoader;

    @Autowired
    public ExampleController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    private List<String> getFiles() throws IOException {
        Resource[] resources = ResourcePatternUtils
                .getResourcePatternResolver(loader)
                .getResources("classpath*:elcordelaciutat/*.txt");

        return Arrays.stream(resources)
                   .map(p -> p.getFilename().toUpperCase())
                   .sorted()
                   .collect(toList());

    }
}

如果要获取所有文件包括的子文件夹中的文件elcordelaciutat,则需要包括以下模式classpath*:elcordelaciutat/**。这将检索子文件夹(包括文件夹)中的文件。获得所有资源后,请根据.txt文件扩展名对其进行过滤。这是您需要进行的更改:

private List<String> getFiles() throws IOException {
    Resource[] resources = ResourcePatternUtils
            .getResourcePatternResolver(loader)
            // notice **
            .getResources("classpath*:elcordelaciutat/**");

    return Arrays.stream(resources)
               .filter(p -> p.getFilename().endsWith(".txt"))
               .map(p -> {
                   try {
                       String path = p.getURI().toString();
                       String partialPath = path.substring(
                           path.indexOf("elcordelaciutat"));
                       return partialPath;
                   } catch (IOException e) {
                            e.printStackTrace();
                   }

                   return "";
                })
               .sorted()
               .collect(toList());
}

假设您具有以下资源文件夹结构:

+ resources
  + elcordelaciutat
    - FileA.txt
    - FileB.txt
    + a-dir
      - c.txt
      + c-dir
        - d.txt
    + b-dir
      - b.txt

过滤后,列表将包含以下字符串:

Java 2022/1/1 18:15:31 有379人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶