java Spring FileNotFoundException。。(无此类文件或目录)
我是Spring MVC的新手。我创建了一个新的spring控制器方法,该方法采用fileoutputstream并将xml写入其中,如下所示:
@RequestMapping(value = "/xml", method = RequestMethod.GET, produces = MediaType.APPLICATION_XML_VALUE)
public final void getMappingsAsXML(HttpServletResponse response) {
Customer customer = getCustomerMappings();
try {
// Generates xml file
xmlHelper.save(customer, new StreamResult(new FileOutputStream("/WEB-INF/content/customermapping.xml")));
// print to browser
// read generated file and write to response outputsteam
} catch (XmlMappingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
但是,上述代码引发以下异常:
java.io.FileNotFoundException: /WEB-INF/content/customermapping.xml (No such file or directory)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:194)
at java.io.FileOutputStream.<init>(FileOutputStream.java:84)
WEB-INF文件夹中已存在内容目录。还有,在spring中有没有更好的方法将文件写入浏览器
[顺便说一句,我用的是maven。]
# 1 楼答案
通过使用
/WEB-INF/content/customermapping.xml
路径,您告诉Java将名为customermapping.xml
的文件写入驱动器根处的WEB-INF/content
目录。这听起来不像你想要的尝试删除前导的
/
但是,在托管web应用程序的同一目录中写入文件可能不是一个好主意,因为一些servlet容器(如Tomcat)在取消部署应用程序时(使用默认设置)会删除整个目录。写入webapp外部的目录要好得多