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 (Unsupport开发者_开发百科edEncodingException 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 ?
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.
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
精彩评论