Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Error Reading an xml file from a servlet

 
pulijala hari
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 64692
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
pulijala hari
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 64692
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since it is not a servlet, i can not


Is it called from a servlet?
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64692
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I used the absolute path temporarily and it works fine.

thank you
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic