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

9

我想知道如何在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.");
    }

但是我遇到了一个问题:
请求处理失败; 嵌套异常为java.lang.NullPointerException


文件已存在? - Ascalonian
不,我想要创建它。 - Giancarlo Ventura Granados
请查看此答案:https://dev59.com/K2Ml5IYBdhLWcg3wJD9S - Soufiane Roui
3个回答

8
如果你想在由getResource()返回的目录中创建一个test.xml文件,请尝试以下操作:
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 的回答中有解释。


这在Windows上失败了。 - N4ppeL

3

看起来你调用 getResource("file/test.xml") 很可能会返回 null。

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

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


1
首先,您不应该将文件写入资源文件夹中,因为每次进行新的构建时都会被删除。相反,将其存储在其他位置,并在属性文件中指定路径。
您可以使用以下方式创建文件:
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();

我不确定,资源文件夹也可以包含在构建中,你觉得测试是如何在部署环境中通过的? - Arsalan Khalid
根据我的理解,资源文件夹的内容/文件可以在jar包的根路径下包含在构建中。但是,我猜您无法读取或编辑它。在部署环境中,您需要通过编写代码和构建/部署脚本将该资源内容复制到您的jar文件可以访问的位置。 - Sahil Chhabra

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接