aspose file tools*
The moose likes Servlets and the fly likes Error Reading an xml file from a servlet Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Error Reading an xml file from a servlet" Watch "Error Reading an xml file from a servlet" New topic
Author

Error Reading an xml file from a servlet

pulijala hari
Ranch Hand

Joined: May 14, 2005
Posts: 70
Hi,

I have a servlet which has to read data from custom.xml file. while i can read the data from a normal class using
<code>
BufferedReader in = new BufferedReader(new FileReader("custom.xml"));
</code>
with out any error.
But i get custom.xml not found in the class path when i try to read the same from a servlet.
where should i keep this custom.xml for a servlet to be accessed under class path?
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61766
    
  67

new FileReader("custom.xml")


Relative file paths are meaningless in web applications because there is no concept of a "current directory".

You will need to locate the file either by using an absolute file path (provided by a context param, property file or some other means other than hard-coding), or if the file is located within the web application, you can employ getResourceAsStream() or getRalPath() to locate the file.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
pulijala hari
Ranch Hand

Joined: May 14, 2005
Posts: 70
Since it is not a servlet, i can not employ getResourceAsStream() or getRalPath() to locate the file in the java class.

So,only thing i can do is through a property file.
Where should i keep this proerty file and how to access the file from the java class.
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61766
    
  67

Since it is not a servlet, i can not


Is it called from a servlet?
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61766
    
  67

My point is that the problem with your code is that you have bound it to a specific environment: one in which the current directory exists and contains the file. You've also hard-coded the file name into the method. These decisions severely limit the reusability and flexibility of the code; as you have seen.

Rather, re-factor the method to recieve either an absolute file path, or an InputStream. That way, it is the responsibility of the environmnet-specific calling code to fnd the file and supply it to the routine which is now flexible and reusable.
pulijala hari
Ranch Hand

Joined: May 14, 2005
Posts: 70
I used the absolute path temporarily and it works fine.

thank you
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Error Reading an xml file from a servlet