我正在使用以下代码从 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 中是否存在某些阻止写入文件的安全措施?
最佳答案
您的代码在传递给 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"));
为文件名使用一个单独的变量可以让您记录它,这样您就可以在开发过程的早期看到意想不到的结果。
关于java - 从 servlet 中写入文件(Deployer :Tomcat),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4482353/