我使用以下代码从Tomcat容器中的servlet写入文件。如果在每次部署期间文件被覆盖,我不担心。
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();
}
但是,文件写入不成功(它不会写入硬盘)。此外,没有任何异常被抓住! Tomcat中是否存在阻止文件写入的安全问题?
答案 0 :(得分:2)
您的代码在传递给getRealPath()
的文件名开头都有“/”和Windows文件分隔符,Java根据当前操作系统解释文件名中的斜杠。
不使用文件分隔符可能会产生更好的结果:
String filename = getServletContext().getRealPath("/WEB-INF/XML.xml");
log.debug("Using XML file: " + filename);
xml_out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename),"UTF8"));
使用单独的文件名变量可以让您记录它,这样您就可以在开发过程的早期看到意外的结果。
答案 1 :(得分:0)
我有同样的问题。 this链接帮助我了解文件在硬盘中的位置 特别是对我来说,它将文件放在此行返回的位置:
System.getProperty( “user.dir来”);
在我的情况下,位置是: C:\ Users \ Myself \ programming \ eclipse for java