views:

351

answers:

2

Hi,

I have recently created a web project in Java using eclipse. I have a servlet which includes a timer task. This timer tasks calls the "writeList" method of an XML Writing class that I have created. This all works fine, and I have verified that it runs every minute using System.out.

When I run my XML Writing class from within eclipse as an application, it works fine. The file is outputted to 'WebContent/test.rdf' without any problems.

However, when it is called by the timer task in my servlet, I am getting the following error:

java.io.FileNotFoundException: WebContent/Test.rdf(No such file or directory)
     at java.io.FileOutputStream.open(Native Method)
     at java.io.FileOutputStream.<init>(FileOutputStream.java:179)
     at java.io.FileOutputStream.<init>(FileOutputStream.java:70)
     at com.XMLWriter.writeList(XMLWriter.java:58)
     at com.ServerTimer$1.run(ServerTimer.java:30)
     at java.util.TimerThread.mainLoop(Timer.java:512)
     at java.util.TimerThread.run(Timer.java:462)

The code at line 58 of XMLWriter is as follows:

fileOut = new FileOutputStream("WebContent/TEST.rdf");
model.write(fileOut);

fileOut is a FileOutputStream, and model is an instance of a Jena model, as I am working with RDF.

Any help would be appreciated, I have been stuck with this for days now! Any questions just let me know!

EDIT: So it is working now, but I want to write the file to the 'WebContent' directory of my Web Project. Is there any way of doing this automatically? I can't get the system to dynamically find that directory.

A: 

It's because the directory does not exist. Either create the directory (programatically or offline) or create the folder on the base path.

Vinnie
A: 

You should never rely on relative paths that way. Using relative paths in Java IO is asking for portability trouble. The java.io.File knows nothing about the web application context it is running in. The actual path would be dependent on the current working directory, which is not per se the same in all environments and depends on the way how you started the server/application. It may become relative to for example C:/Tomcat/bin and your TEST.rdf is obviously not there. Always use absolute paths, i.e. use the full disk file system path.

In case of a JSP/Servlet webapplication you can use ServletContext#getRealPath() to convert a relative web path to an absolute disk file system path which you can use further in Java IO stuff. A relative web path is rooted in the public webcontent. Assuming that /TEST.rdf is located in the root of the public webcontent, then you can get an absolute disk file system path for /TEST.rdf inside a servlet the following way:

String relativeWebPath = "/TEST.rdf";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
File file = new File(absoluteDiskPath);
BalusC
Worked brilliantly! Thanks a lot!
CGOBE