Search code examples
javafilejakarta-eefile-iojava-6

In Java is it possible to get a directory file listing inside a WAR classpath using a resource path?


I have a list of files in a directory on the classpath that I need to read, and would prefer using the File API, but it appears I can't do that within an archive. This works on my local environment unit test, but when I deploy as a WAR inside an EAR, the listing of the files returns null:

File dir = new File(getClass().getClassLoader().getResource("mydir").getPath());
File[] files = dir.listFiles();

Solution

  • You can't use the File API when the war isn't unpacked, but you can use the Servlet API.

    The getResourcePaths method of ServletContext can be used to retrieve all members of a "directory", and then getResource or getResourceAsStream to retrieve the contents of a file in the directory.

    for (String s : context.getResourcePaths("foo")) {
        InputStream contents = context.getResourceAsStream(s);
        //do something with the contents
    }