The system cannot find the file specified but file exists

Tal Angel :

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".

Anish B. :

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 :

  1. 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.

  2. 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)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=117850&siteId=1