【问题标题】:How to get a list of file paths in a specific folder in Spring app如何在Spring应用程序中获取特定文件夹中的文件路径列表
【发布时间】:2018-04-17 07:08:11
【问题描述】:

我需要特定文件夹中的文件路径列表。我希望它在应用程序打包到 jar 后才能工作,因此使用 File 对象可能不起作用。

路径需要以静态文件夹开头,例如:

/static/json/networks/network.json

到目前为止,我已经尝试过:

File folder = new File("src/main/resources/static/json/networks/pools");
File[] listOfFiles = folder.listFiles();

但它给了我一个以以下开头的路径列表:

/src/main/resources/static/etc

我无法将其与 ClassPathResource 一起使用。我也试过:

ClassLoader classLoader = MethodHandles.lookup().getClass().getClassLoader();
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(classLoader);

但这给了我文件的绝对路径。

【问题讨论】:

    标签: java spring spring-boot filepath


    【解决方案1】:

    您可以尝试一个名为 maven-shared-utils 的库(检查类 DirectoryScanner)。

    或者你可以自己做:

    @SpringBootApplication
    public class DemoApplication {
    
    public static void main(String[] args) {
    
        SpringApplication.run(DemoApplication.class, args);
    
        final String baseFolder = "folder1";
        try {
        Path pathBase = Paths.get(ClassLoader.getSystemResource(baseFolder).toURI());
    
            Files.walk(pathBase.resolve("folder2/folder3"))
                    .filter(Files::isRegularFile)
                    .forEach(f -> System.out.println(pathBase.relativize(Paths.get(f.toUri()))));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    
     }}
    

    此代码将为src/main/resouces/folder1/folder2/folder3/* 中的文件打印:

    文件夹2/文件夹3/fil2.json

    文件夹2/文件夹3/file3.kt

    文件夹2/文件夹3/file1.xml

    【讨论】:

    • 据我所知,我还不熟悉 Java 8。如何访问列表? :f
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-21
    • 2019-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多