FileNotFoundException when reading .xml file to parse

ericso picture ericso · Apr 5, 2010 · Viewed 8.5k times · Source

I'm writing a program in Java where I read in data from an XML file and parse it. The file is imported into a folder named "Resources" in the src directory of my project. I'm using Eclipse. When I run the program, I get the following error:

java.io.FileNotFoundException: /Users/thechiman/Dropbox/introcs/PSU SOC Crawler/resources/majors_xml_db.xml (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:106)
at java.io.FileInputStream.<init>(FileInputStream.java:66)
...

The relevant code is here:

private void parseXML() {
    //Get a factory
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    try {
        //Use factory to get a new DocumentBuilder
        DocumentBuilder db = dbf.newDocumentBuilder();

        //Parse the XML file, get DOM representation
        dom = db.parse("resources/majors_xml_db.xml");
    } catch(ParserConfigurationException pce) {
        pce.printStackTrace();
    } catch(SAXException se) {
        se.printStackTrace();
    } catch(IOException ioe) {
        ioe.printStackTrace();
    }
}

I do not understand why I'm getting the FileNotFoundException when the file is there. Thanks for the help.

Answer

skaffman picture skaffman · Apr 5, 2010

With DocumentBuilder.parse(String), the argument is interpreted as a URI, and in this case, it's going to be a relative URI (the string you're giving it is not a "full" URI). What it's relative to is a bit ambiguous at this point, without further information on your setup. The runtime will be interpreting it as relative to something, but it's not clear here what that something is.

You'll get more reliable results by using one of the other parse methods, such as parse(File) or parse(InputStream). In each case, there's no ambiguity as to what you're asking it to parse.

If you decide to construct a File object first (to pass to parse later), then you have a more manageable problem of making sure that that file exists (using File.exists() and so on). If you can't get that far, then your problem isn't with DocumentBuilder or the DOM, it's with basic file paths. Remember that if you use relative file paths (e.g. new File("resources/majors_xml_db.xml")) then this will be resolved relative to the working directory of the process. If it works or not depends on how you launch your program.