'Spring List all files in static directory

I use Spring with embeded Tomcat and a War file in prodution.

I need to list all files in the "static" directory. It's like 4 days I m on it This kind of code not working :

Stream.of(new File(dir).listFiles()

It lists the files where the war is located but the static directory is inside the war

With this code I arrive to read a file inside the war : Thread.currentThread().contextClassLoader?.getResourceAsStream(path)?.bufferedReader()?.use(BufferedReader::readText)

But it's not working with a directory And now i have no idea how i can list all files inside the static directory



Solution 1:[1]

I found a solution Not sure it's the best and clean but it's worked I use 2 way to do it, one for developpment and the other when it's package inside war

loadFilesFromDirectory("/static")

fun listFilesFromDirectory(path: String, request: HttpServletRequest? = null): List<String> {
    return if (request == null || request.requestURL.contains("localhost")) {
       //Don't work on war but work on IDE
       Thread.currentThread().contextClassLoader?.getResourceAsStream(path) 
            ?.bufferedReader()?.use(BufferedReader::readText)?.split("\n")
            ?.filter { it.endsWith(".html") }
            ?: throw Exception("Non trouvé :$path")
    } else {
        //Not work on IDE but work on war
        val root: URL = request.servletContext.getResource("/WEB-INF/classes/$path")
        var rootPath: String = root.path
         rootPath = rootPath.substring(rootPath.indexOf("/WEB-INF"), rootPath.length)
        return request.servletContext.getResourcePaths(rootPath).map {
                    it.replace(".*/", "")
                }.filter { it.endsWith(".html") }
        }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anthone