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".
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 :
new File("MyFolder\Test.xml")
- This will not work because you have not provided the absolute path. You have to use classloader to get file from classpath (in that case, you don't have to mention the full path). Classloader brings the full absolute path for you. Remember: java.nio.File
needs absolute path for its working.
If you want to read file from any arbitrary location, then you have to specify the full path for that. (Assuming that you are trying to access the file outside)