0

I use tomcat server, and try to call a java class from servlet, that class has method which will return system current directory path. It's result is difference with the one when I run form main method in that class.

  • from main method: "D:\Projects\Eclipse\Assignment" (which is where i place my project)
  • from servlet: "D:\IDE\eclipse helios" ( which is where i place my eclipse)

With this I have trouble to access my xml file in my project folder( file not found exception when I call a class from servlet). I want the same result when call from servlet as when run main method. How can I do that?

I would appreciate any advice you could give me to, or any articles that you could recommend.

Thank you.

Lucas Van
  • 3
  • 2
  • 1
    Related: http://stackoverflow.com/questions/2308188/getresourceasstream-vs-fileinputstream – BalusC Feb 20 '12 at 02:07

2 Answers2

4

Why are you trying to access your resources from the filesystem? The expected method of accessing resources from any JAR, including webapps, is using getResourceAsStream:

http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)

i.e. add the folder containing your resource to the build path, and use YourClassName.class.getResourceAsStream("/foo.xml") to access it.

FauxFaux
  • 2,445
  • 16
  • 20
  • 1
    That's all well and good if the resource is read-only, if it's packaged as a standard part of the .jar (i.e. guaranteed to be in that location in the .jar), and if there even *is* a .jar (or .war, or .ear). Otherwise, just for reading and writing files ... the file system is a perfectly appropriate place for ... files :) IMHO... – paulsm4 Feb 20 '12 at 03:36
  • In other words: the appropriate tool for the job. getResourceAsStream(), FileInputStream() and even HttlUrlConnection() are all perfectly appropriate choices, depending on the situation. IMHO... – paulsm4 Feb 20 '12 at 03:40
0

Q: You understand why "current directory" is in two different places, correct? One place is where you're running your Java program (when you "Run As, Java Program"), and the other place is where you're running your web server (when you "Run As, Web App").

Q: For your current situation, why not just use an absolute path (e.g. "d:\projects\data")?

paulsm4
  • 114,292
  • 17
  • 138
  • 190