Peter Ambruzs
Peter Ambruzs

Reputation: 8223

Listing resources from a resource folder

I created a data folder beside the js folder in resource/static at the backend of my spring boot application. I want to list its content in a selection for the user. I was able to list it if I use the File and Path functions of the base Java. But I don't like this solution, because the path could change in different environment of our system. I can load a file with org.springframework.core.io.ResourceLoader. I like this solution better as it is independent of the file path of my system. But I did not found the way to list the files in a given resource folder. Do you have any idea?

Upvotes: 0

Views: 859

Answers (2)

Peter Ambruzs
Peter Ambruzs

Reputation: 8223

Finally I moved my data folder to the WEB-INF. And I can list the content of it with the following code:

@Autowired
ServletContext context; 

public Collection<String> getFileList(String path) {
    Collection<String> result = new ArrayList<String>();

    Set<String> paths = context.getResourcePaths(path);
    for (String p : paths) {
        String[] parts = p.split("/");
        result.add(parts[parts.length-1]);
    }
    return result;
}

And I call it with the following parameter:

    getFileList("/WEB-INF/data");

This solution works if the WEB-INF folder is unpacked during deploy. And also works when the data folder remains in the war archive.

Upvotes: 1

kraikov
kraikov

Reputation: 53

Check this out :) You can also read about Java Reflection

Upvotes: 0

Related Questions