I have a test web app that needs to process some files (they happen to be Microsoft Office documents, but that’s not really relevant).
The web app could be installed on a number of different machines, running Windows or Linux and needs to just work, so the files need to be stored within the war and accessed from there.
The structure of the source is:
- [root]
- src
- main
- resources
- docs
- Doc1.docx
- Doc2.docx
- Show1.ppt
- docs
- resources
- main
- src
This is all built using maven, so I don’t have to do anything more in order to include the resources in my war file.
The trick to accessing the resources as File objects is to use getResource to get a URL to the file, and then to construct the File object using the getFile method of the URL.
Once you’ve got access to the File object you can do all the usual operations with it, including loading the entire file into memory, which is also shown below (note that in normal cases you should check the size of a file before loading it into memory, but these files are resources, I created them and I know how big they are).
public class ClassWotDuzzStuff
{
private static final Log log = LogFactory.getLog( ClassWotDuzzStuff.class );
private static final String[] inputs = new String[] {
"/docs/Show1.ppt",
"/docs/Doc2.docx",
"/docs/Doc1.docx"
};
public void doStuffWithResources()
{
for( String input : inputs )
{
URL currentFileUrl = this.getClass().getResource( input );
File currentFile = new File( currentFileUrl.getFile() );
byte[] contents = new byte[ (int)currentFile.length() ];
try
{
FileInputStream currentInputStream = new FileInputStream( currentFile );
currentInputStream.read( contents );
}
catch( FileNotFoundException ex )
{
log.warn( "The file \"" + input + "\" is listed as a resource, but doesn't seem to exist." );
continue;
}
catch( IOException ex )
{
log.warn( "The file \"" + input + "\" could not be read." );
continue;
}
doStuff( File, contents );
}
}


