简体   繁体   English

Spring FileNotFoundException ..(没有此类文件或目录)

[英]Spring FileNotFoundException .. (No such file or directory)

I'm new to Spring MVC. 我是Spring MVC的新手。 I created a new spring controller method that takes an fileoutputstream and writes xml to it as follows: 我创建了一个新的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();
        }
}

However, the above code throws the below exception: 但是,以上代码引发以下异常:

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)

The content directory already exists in the WEB-INF folder. 内容目录已经存在于WEB-INF文件夹中。 Also, are there any better ways to write a file to browser in spring? 另外,春季有没有更好的方法将文件写入浏览器?

[BTW, I'm using maven.] [顺便说一句,我正在使用Maven。]

By using a path of /WEB-INF/content/customermapping.xml you are telling Java to write a file named customermapping.xml to the WEB-INF/content directory at the root of the drive. 通过使用/WEB-INF/content/customermapping.xml的路径,您将告诉Java将名为customermapping.xml的文件写入驱动器目录下 WEB-INF/content目录。 This doesn't sound like what you want. 这听起来不像您想要的。

Try removing the leading / . 尝试删除前导/

However it's probably a bad idea to write to files within the same directory hosting your web application, as some servlet containers like Tomcat simply remove the entire directory when you undeploy the application (with the default settings). 但是,在托管Web应用程序的同一目录中写入文件可能不是一个好主意,因为诸如Tomcat之类的servlet容器在取消部署应用程序时使用默认设置只是删除了整个目录。 Much better to write to a directory external to the webapp. 最好写入Webapp外部的目录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM