将文件写入Spring中的resources文件夹

时间:2015-01-12 19:45:31

标签: java spring

我想知道,如何将文件写入Spring MVC项目中的资源文件夹。 我将web-dispatcher-servlet.xml中的资源路径定义为
<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.");
    }

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

3 个答案:

答案 0 :(得分:4)

如果要在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.");
}

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

答案 1 :(得分:2)

您对 getResource(&#34; file / test.xml&#34;)的调用可能会返回null。

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

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

答案 2 :(得分:0)

首先,您不应该写入资源文件夹中的文件,因为每当您进行全新构建时它都会被删除。而是将其存储在其他位置,并在属性文件中指定路径。

您可以使用以下方式创建文件:

String rootPath = System.getProperty("user.dir");
File file = new File(StringUtils.join(rootPath, "/any/path/from/your/project/root/directory/" , "test.xml"));
//Below commented line is what you wish to do. But I recommend not to do so.
//File file = new File(StringUtils.join(rootPath, "/out/resources/file/" , "test.xml"));
file.createNewFile();