Tuesday, June 24, 2014

Play 2 framework access files in WAR

So you've created WAR files from your Play project, see Play 2 framework WAR file. But how to fetch files within you WAR file.

I previously used:
new File(play.Play.application().path().toString() + "//mydirectory//myfile.txt");
which works fine when running on the Play "stack".

After exporting to WAR file the path ended up looking in the application home directory, e.g. /home/<runninguser>/.
Still works for files not in the WAR, since they are expected to be found here anyways.

Solution for my WAR files:
InputStream is = Play.class.getResourceAsStream("/mydirectory/myfile.txt"");
StringWriter writer = new StringWriter();
IOUtils.copy(is, writer, Charsets.UTF_8);

Source: http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string and http://stackoverflow.com/questions/6888343/getting-a-resource-file-as-an-inputstream-in-playframework

Note: Jetty will unpack you WAR file to a temp directory, either /tmp or below you application path /home/<runninguser>/ so this is what you are accessing. Remember not to have a script deleting these files as this will crash your web application.

No comments:

Post a Comment