Scientist
Scientist

Reputation: 1464

java reading xml file from relative path using getResource()

I have a xml file placed at location pkgName/src/main/resources/Config.xml

I am trying to read it from java file as

package com.xstreamparsing.parsers;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.net.URL;

import javax.security.auth.login.Configuration;

import com.thoughtworks.xstream.XStream;

public class XStreamConfigParser {

    public static void main(String[] args) throws FileNotFoundException {

        URL url = XStreamConfigParser.class.getResource("config.xml");
        File file = new File(url.getPath());

        FileReader fileReader = new FileReader(file);  // load our xml 

When i run the program i am unable to read it. i followed the link :

Reading a file from a relative path

Unfortunately i could not succeed. Please suggest best and universal file to read file from java class.

Upvotes: 0

Views: 3344

Answers (1)

Puce
Puce

Reputation: 38132

XStreamConfigParser.class.getResource("config.xml");

This will search relative to XStreamConfigParser, in this case in the same package.

Try instead:

XStreamConfigParser.class.getResource("/config.xml");

This will start looking at the root of your output dir/ jar file.

Alternatively move the file to:

src/main/resources/com/xstreamparsing/parsers/config.xml

Also make sure sure your using the correct case (Config.xml vs config.xml).

Upvotes: 2

Related Questions