3

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();
  • How would I get a list of files from the input stream? I don't know their names, which is why I need a listing of actual File objects. –  Jun 25 '12 at 19:03

2 Answers2

2

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
}
Sean Reilly
  • 21,526
  • 4
  • 48
  • 62
  • I thought that might be the case. If anywhere, do you know where in the Java docs this is stated (regarding a file listing for an unpacked WAR)? –  Jun 25 '12 at 19:12
  • Nowhere explicitly (that I know of) in javadoc. It's a consequence of the fact that a servlet engine is not obligated to place the contents of the WAR on the filesystem at all. That nugget is mentioned in the Servlet JSR, but I don't have a specific citation in javadoc for you — not everything is in javadoc. – Sean Reilly Jun 25 '12 at 19:16
0

If you're using Java SE 7 try:

Path jarPath = Paths.get(...);
try (FileSystem jarFS = FileSystems.newFileSystem(jarPath, null)) {
    Path dirJarPath = jarFS.getPath("/foo/mydir");
    <use a FileVisitor and Files.walkFileTree>
}

http://docs.oracle.com/javase/7/docs/api/java/nio/file/FileVisitor.html

Puce
  • 37,247
  • 13
  • 80
  • 152
  • @Puce: How would you even obtain the path to the jar file when the ear containing the war isn't unpacked? Doing that in a portable fashion isn't exactly straightforward. Even if it was, I'm worried that repeatedly uncompressing the jar file won't be very performant. – Sean Reilly Jun 25 '12 at 19:19
  • @SeanReilly Recently, I've added a utility method to the SoftSmithy Utility Library to get the jar of a class, but I haven't released it yet. You can find the code here (license: CDDL): http://softsmithy.hg.sourceforge.net/hgweb/softsmithy/lib/main-golden/file/058faa0f7621/lib-core/src/main/java/org/softsmithy/lib/nio/file/JarFiles.java About the performance: you will have to profile it if there is an issue – Puce Jun 25 '12 at 19:21
  • @Sean Reilly: you don’t need the path to the jar file when you have a URL pointing to a resource inside it. See [here](http://stackoverflow.com/a/36021165/2711488) for a complete example… – Holger Mar 15 '16 at 20:23