File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes Reading file from a servlet packaged in war Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Reading file from a servlet packaged in war" Watch "Reading file from a servlet packaged in war" New topic

Reading file from a servlet packaged in war

Pradeep bhatt
Ranch Hand

Joined: Feb 27, 2002
Posts: 8927

Is it possible to read a file packaged in a war file from a servlet class that is also packaged in the same war file. If yes how do I specify the path of the file?
Thanx in adv

Tim Holloway
Saloon Keeper

Joined: Jun 25, 2001
Posts: 17410

This is a variant of a popular question around here.
The problem is that you're assuming that the appserver works with WARs. Actually, a J2EE appserver (and really, Java in general) isn't expected to CARE where its classes and resources came from - if, in fact they were ever even in files to begin with - much less packages in an archive file.
When you invoke a Java classloader (as the appserver is doing), you are actually simply requesting that it return a class/resource from WHEREVER it can find it. And while that CAN be a ".class" file or component of a WAR (or EAR or JAR), it might just as easily have been magically conjured up from a parallel universe. Even though YOU know where it came from, the class loading mechanism isn't allowed to make that assumption.
So the short answer is "no". The ACTUAL answer is, "yes" - IF: 1, you embed it in a class; 2, you place it in a properties file; 3, you resort to some sort of gimmick like retrieving the file in the same way properties files are (by requesting them through the classloader); 4, you place the file in the content area of the WAR (where the JSP's are) and do an internal server request.
All of the above solutions are only good if the file is read-only. For read/write access, you can only reliably locate the file by passing its location as an absoute path to a startup servlet or some similar mechansim that makes that value accessible to the web application.
[ April 23, 2002: Message edited by: Tim Holloway ]

An IDE is no substitute for an Intelligent Developer.
Pradeep bhatt
Ranch Hand

Joined: Feb 27, 2002
Posts: 8927

It is possible to read a file by using
getServletContext().getResourceAsStream("/WEB-INF/web.xml"); which will return an InputStream object from which u can read the file.
I agree. Here's the link:
subject: Reading file from a servlet packaged in war
It's not a secret anymore!