代码之家  ›  专栏  ›  技术社区  ›  Maciaz

如何在Spring app中获取特定文件夹中的文件路径列表

  •  1
  • Maciaz  · 技术社区  · 6 年前

    我需要一个特定文件夹中文件路径的列表。我希望在将应用程序打包到一个罐子中后,它才能工作,所以使用 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);
    

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

    1 回复  |  直到 6 年前
        1
  •  1
  •   Akli REGUIG    6 年前

    你可以试试一个叫做 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/文件2。json

    文件夹2/文件夹3/文件3。千吨级

    文件夹2/文件夹3/文件1。xml