javajava-io

The system cannot find the file specified but file exists


I'm trying to manipulate my XML file called Test.XML.

I can see the file in my folder and I can open it. Code:

DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();            
domFactory.setIgnoringComments(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse(new File("MyFolder\Test.xml"));

I am getting this error:

java.io.FileNotFoundException: C:\MyFolder\Test.xml (The system cannot find the file specified)

Why can't the code open/read my file, but other programs like Notepad++ can do so?

***Note: the real name of the file is "Use-cases\testSuitesA_E_1002+${user}3_12022016+${date}2_2.5.xml".


Solution

  • Please modify your code to this :

    ClassLoader classLoader = ClassLoader.getSystemClassLoader();
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setIgnoringComments(true);
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse(new File(classLoader.getResource("MyFolder/Test.xml").getPath()));
    System.out.println(doc.getDocumentElement());
    

    For this code to run, build the project for .class files. Classloader needs to have .class files. Otherwise, it will not able to read folder or files from classpath.

    Note :