在Spring中将文件写入资源文件夹

Gia*_*dos 3 java spring

我想知道,如何在Spring MVC项目中将文件写入资源文件夹。我在web-dispatcher-servlet.xmlas中定义了资源路径
<mvc:resources mapping="/resources/**" location="/resources/" />

我阅读了有关如何从资源文件夹读取文件的示例。但是我想将文件写入资源文件夹。我试过了

ClassLoader classLoader = getClass().getClassLoader();
    File file = new File(classLoader.getResource("file/test.xml").getFile());
    if (file.createNewFile()) {
        System.out.println("File is created!");
    } else {
        System.out.println("File already exists.");
    }
Run Code Online (Sandbox Code Playgroud)

但是我得到了
Request processing failed; nested exception is java.lang.NullPointerException

Sha*_*ush 6

如果要test.xml在返回的目录中创建文件getResource(),请尝试以下操作:

File file = new File(classLoader.getResource(".").getFile() + "/test.xml");
if (file.createNewFile()) {
    System.out.println("File is created!");
} else {
    System.out.println("File already exists.");
}
Run Code Online (Sandbox Code Playgroud)

getFile()如Reid的答案所述,调用不存在的目录或文件将返回null。


Rei*_*son 3

看来您对getResource("file/test.xml") 的调用可能返回 null。

我很好奇,您的 XML 文件的完整路径是什么?为此,资源目录需要放置在您的webapp目录中。如果您尝试使用标准 Java 资源结构 (src/main/resources),那么 Spring MVC 映射将不起作用。

编辑:看到您对 @Ascalonian 评论的回答后,这将不起作用,因为该文件不存在。就像我之前提到的,getResource("file/test.xml")将返回 null,因此以下对getFile() 的调用将抛出 NPE。也许您应该检查getResource是否返回 null 并将其用作需要创建文件的指示。