2023 - CodeByAkram

Read Files from classpath or resource folder and subfolder - Java

 The below code shows hot to read the list of resources(files) from a classpath folder and subfolder.

Below is the example code



import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.util.*;

public class ReadResourceFiles {

    public static void main(String[] args) throws IOException {
        List resourceFolderFiles = getResourceFolderFiles("static");
        resourceFolderFiles.stream().filter(f -> f.endsWith(".json")).forEach(System.out::println);
    }

    static List getResourceFolderFiles(String folder) {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        URL url = loader.getResource(folder);
        String path = url.getPath();
        File file = new File(path);
        List files = new ArrayList<>();
        if(file.isDirectory()){
            try {
                Files.walk(file.toPath()).filter(Files::isRegularFile)
                        .filter(f-> f.toFile().getName().toLowerCase().endsWith(".json"))
                        .forEach(f -> files.add(f.toFile().getPath()));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }else if(file.getName().toLowerCase().endsWith(".json")){
            files.add(file.getPath());
        }
        return files;
    }
}