fftk4323
fftk4323

Reputation: 130

Loading a XML file as a resource

I am making a game that uses xml files to store data. I am trying to build a class that will load a template xml file to hold a variety of data. I would like to use this template file as a JAR resource, however I am running into a problem where it will say the file is empty (java.lang.NullPointerException)

My question is, how do I set up the files to be used as resources correctly?

The code:

public XMLFileReader(String Item_Name) {

    URL test = this.getClass().getResource("Reasource/Example.txt");

    System.out.print(test.getPath());

    try {
        URL is = this.getClass().getResource("Reasources/" + Item_Name);

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(is.getFile());

        doc.getDocumentElement().normalize();

        System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

        NodeList nList = doc.getElementsByTagName("staff");

        System.out.println("----------------------------");

        for (int temp = 0; temp < nList.getLength(); temp++) {

            Node nNode = nList.item(temp);

            System.out.println("\nCurrent Element :" + nNode.getNodeName());

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                Element eElement = (Element) nNode;

                System.out.println("Staff id : " + eElement.getAttribute("id"));
                System.out.println("First Name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent());
                System.out.println("Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
                System.out.println("Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());
                System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());
            }
        }
    }
}

public static void main(String[] args){
    new XMLFileReader("Example.xml");
}

The file structure:

 Main Project
 |
 |-Reasources
 |      |
 |      |-Example.txt
 |
 |-XMlTest
     |
     |-XmlFileReader

The Error

java.lang.NullPointerException
at Utils.File_Utils.XMLFileReader.<init>(XMLFileReader.java:32)
at Utils.File_Utils.XMLFileReader.main(XMLFileReader.java:68)

Upvotes: 0

Views: 91

Answers (1)

K139
K139

Reputation: 3669

Make sure the Resources\Example.txt file is in classpath.

if you are running from cmd line then,

java -cp Resources\Example.txt YourClassFile

and also you are using absolute classpath, instead use relative path like /Resources or ./Resources.

Upvotes: 1

Related Questions