Reading the contents of a .WAR file from a Web-app

A lot of people seem to wind up on one of our other pages when trying to figure out how to read the contents of a .WAR file from the Web-app itself, so we've created this page to help those people.

First of all, we think the easiest way to do it is to use our javas library and simply call the helper method for doing just that, like so:

String content = javas.servlet.
        ServletContexts.getFileFromWar(context, "/path/to/file.ext");

And if you want to see exactly how it's done you can trace through the source and decipher each of the calls it makes.

In case you'd rather just know how it's done in general terms, here's the explanation:

You can get a handle to a file inside the .WAR your code is executing from by calling the .getResource() or .getResourceAsStream() methods. The first returns a URL and the second returns a Stream. The path of least resistance is to use the second method and get the stream, then read the contents of the file from the stream, however you would normally do that. (We highly recommend buffering for performance reasons).

Of course you can avoid having to write all that code by using our javas library to handle that piece too, by using our Streams helper like so:

byte[] bytes = Streams.readByteArray(stream);

And then you can turn that into a String like so:

String data = new String(bytes);

And of course if you chain this altogether you get:

String data = new String(
        Streams.readByteArray(context.getResourceAsStream(path)));

Which is exactly what our ServletContexts.getFileFromWar() method does, so now you might as well just use that. :)

So, we hope this helps, and if we've convinced you, but you missed the other links, you can check out our javas library right here.