如何从资源文件夹中获取文件.Spring框架

Tom*_*lly 19 java spring-mvc fileinputstream java-io

我正在尝试解组我的xml文件:

public Object convertFromXMLToObject(String xmlfile) throws IOException {
    FileInputStream is = null;
    File file = new File(String.valueOf(this.getClass().getResource("xmlToParse/companies.xml")));
    try {
        is = new FileInputStream(file);
        return getUnmarshaller().unmarshal(new StreamSource(is));
    } finally {
        if (is != null) {
            is.close();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但我得到这个错误:java.io.FileNotFoundException:null(没有这样的文件或目录)

这是我的结构:

在此输入图像描述

为什么我无法从资源文件夹中获取文件?谢谢.

更新.

重构后,

URL url = this.getClass().getResource("/ xmlToParse/companies.xml"); 文件文件=新文件(url.getPath());

我可以更清楚地看到错误:

java.io.FileNotFoundException:/content/ROOT.war/WEB-INF/classes/xmlToParse/companies.xml(没有这样的文件或目录)

它试图找到WEB-INF/classes /我在那里添加了文件夹,但仍然收到此错误:(

在此输入图像描述

jon*_*ckt 45

尝试将一些XML文件加载到我的测试类中时遇到了同样的问题.如果您使用Spring,可以从您的问题中建议,最简单的方法是使用org.springframework.core.io.Resource--一个Raphael Rot h已经提到过.

代码非常简单.只需要声明的类型的字段org.springframework.core.io.Resource,并标注其org.springframework.beans.factory.annotation.Value -这样的:

@Value(value = "classpath:xmlToParse/companies.xml")
private Resource companiesXml;
Run Code Online (Sandbox Code Playgroud)

要获得所需的InputStream,只需调用即可

companiesXml.getInputStream()
Run Code Online (Sandbox Code Playgroud)

你应该没事:)

但是,原谅我,我要问一句:为什么要实现与Spring的帮助XML解析器?有很多建设:)例如,对于Web服务也有很好的解决方案,马歇尔你个XML转换为Java对象和背...


小智 13

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("fileName").getFile());
Run Code Online (Sandbox Code Playgroud)

  • 一旦你将此 spring 项目部署到 jar 中,这个问题就会中断。请参阅/sf/ask/1427247881/ (2认同)

Rap*_*oth -2

您应该给出绝对路径(因此添加加载 \xc2\xb4/\xc2\xb4,其中资源文件夹是根文件夹):

\n\n
public Object convertFromXMLToObject(String xmlfile) throws IOException {\n    FileInputStream is = null;\n    File file = new File(String.valueOf(this.getClass().getResource("/xmlToParse/companies.xml")));\n    try {\n        is = new FileInputStream(file);\n        return getUnmarshaller().unmarshal(new StreamSource(is));\n    } finally {\n        if (is != null) {\n            is.close();\n        }\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n