Java – how to get files from a resource folder Spring framework

I tried to dissolve my XML file:

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();
        }
    }
}

But I got this error: Java io. FileNotFoundException: null (no such file or directory)

This is my structure:

Why can't I get files from the resource folder? thank you.

to update.

After reorganization,

URL url = this. getClass(). getResource(“/ xmlToParse / companies.xml”); File file = new File(url.getPath());

I can see the error more clearly:

java. io. FileNotFoundException:/content/ROOT. war/WEB-INF/classes/xmlToParse/companies. XML (no such file or directory)

It tries to find WEB-INF / classes / I have added a folder, but still get this error:(

Solution

I have the same problem trying to load some XML files into my test class If you use spring, you can make suggestions from your questions. The easiest way is to use org springframework. core. io. Resource – Raphael Roth

The code is really direct Just declare a type of org springframework. core. io. Resource field and use org springframework. beans. factory. annotation. Value comment: like this:

@Value(value = "classpath:xmlToParse/companies.xml")
private Resource companiesXml;

To get the required InputStream, simply call

companiesXml.getInputStream()

You should be fine:)

But forgive me, I have to ask one thing: why implement an XML parser with the help of spring? There are many constructions:) for example, for web services, there is a good solution to compile your XML into Java objects and return

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>