Bikash Gyawali
Bikash Gyawali

Reputation: 1058

Writing to file from within a servlet(Deployer:Tomcat)

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 ?

Upvotes: 0

Views: 5126

Answers (2)

Achi Even-dar
Achi Even-dar

Reputation: 501

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

Upvotes: 0

rsp
rsp

Reputation: 23383

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.

Upvotes: 2

Related Questions