0

I am using the following code to write to a file from a servlet in Tomcat container. I don't worry if the file gets overwritten during each deploy.

BufferedWriter xml_out = null;
try {
    xml_out = new BufferedWriter(new OutputStreamWriter(
            new FileOutputStream(getServletContext().getRealPath("/")
                + File.separator + "WEB-INF" + File.separator
                + "XML.xml"), "UTF8"));
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
try {
    xml_out.write(xml);
    xml_out.flush();
    xml_out.close();
} catch (IOException e) {
    e.printStackTrace();
}

However, the file writing is not successful (it doesn't get written in the hard disk). Also, there isn't any exception that gets caught! Is there some security thing in Tomcat that is preventing the file from being written ?

Mr_and_Mrs_D
  • 32,208
  • 39
  • 178
  • 361
Bikash Gyawali
  • 969
  • 2
  • 15
  • 33

2 Answers2

2

Your code has both "/" and the windows file separator at the start of the filename passed to getRealPath(), Java interprets slashes in filenames according to the current OS.

Not using the file separators might give a better result:

String filename = getServletContext().getRealPath("/WEB-INF/XML.xml");

log.debug("Using XML file: " + filename);

xml_out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename),"UTF8"));

Using a separate variable for the filename lets you log it so you can see unexpected results early in de development process.

rsp
  • 23,135
  • 6
  • 55
  • 69
  • This didn't work either! And I don't know how you used the log.debug method? Is log a standard class in java or I have to download some packages to use it? – Bikash Gyawali Dec 19 '10 at 10:19
  • @Bikash, you can use an instance of `java.util.logging.Logger` or use the log4j library for instance (or for the time being simply use `System.out`) you might write the file in a different location than what you expect. – rsp Dec 19 '10 at 10:54
  • Yeah, the file was written somewhere else. I checked for it, and edited the path name to get the correct destination. Thanks. – Bikash Gyawali Dec 19 '10 at 13:02
0

I has the same issue. this link helped me to understand where the file was in the hard disk.
Specifically for me, it put the file in the location that is returned by this line:

System.getProperty("user.dir");

In my case the location was: C:\Users\Myself\programming\eclipse for java

Community
  • 1
  • 1
Achi Even-dar
  • 427
  • 1
  • 10
  • 20