struts-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Vijay Balakrishnan <>
Subject RE: Opening/reading a file from a Struts application...
Date Tue, 29 Jul 2003 19:25:30 GMT
Check this class created by Jason Hunter of fame
to locate a file on the classpath first and then class loader getResource().


-----Original Message-----
From: Craig R. McClanahan [] 
Sent: Tuesday, July 29, 2003 11:36 AM
To: Struts Users Mailing List
Subject: Re: Opening/reading a file from a Struts application...

On Tue, 29 Jul 2003, Davide Bruzzone wrote:

> Date: Tue, 29 Jul 2003 11:57:41 -0600
> From: Davide Bruzzone <>
> Reply-To: Struts Users Mailing List <>
> To: Struts Users Mailing List <>
> Subject: Opening/reading a file from a Struts application...
> Greetings all...
> I'm trying to load and read a text file (on the server's filesystem) 
> from within a Struts application. I'd like to be able to put the file 
> in the WEB-INF, or the WEB-INF/classes directory, but am having 
> trouble finding the file (i.e. I'm having trouble obtaining the path 
> that I need in order to open the file), and reading it...
> Here's what my research has turned up:
> // Something like this will return an InputStream. This is fine for 
> properties files // since you can load a properties file by passing an 
> InputStream to the load method
> // on a Properties object
> Thread.currentThread().getContextClassLoader().getResourceAsStream("my.p
> roperties");

This only works on files visible to the class loader (i.e. files in
/WEB-INF/classes, or packaged in JARs inside /WEB-INF/lib).  To read general
resources in your webapp, try ServletContext.getResourceAsStream()
instead.  You pass it a context-relative path like "/WEB-INF/".

> The problem with this is that the methods that I'm using to read the 
> contents of files takes either a string that represents the file name, 
> or a File object... The methods then calculate the file's length, read 
> the file into an array of bytes, and return the contents of the array 
> in various forms (i.e. An array of bytes, a string, etc.).

That's not going to be portable, because you cannot assume that webapp
resources actually live in the filesystem - you might be running straight
from a WAR file, or in a container that puts all the static resources in
BLOBs in a database, or ...

If you really need file i/o access to this stuff, you should create an
initialization parameter pointing at the directory containing the relevant
files, and then access then outside your webapp hierarchy.

> Does anyone have any suggestions about how best to go about doing this 
> (I could change the methods that read the contents of files into 
> strings, but I'm not sure exactly how to go about doing this).
> Any help would be greatly appreciated...
> Cheers...
> Dave


To unsubscribe, e-mail:
For additional commands, e-mail:

View raw message