我想操纵我的所谓的test.xml XML文件。
我可以看到我的文件夹中的文件,我可以打开它。码:
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setIgnoringComments(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse(new File("MyFolder\Test.xml"));
我得到这个错误:
java.io.FileNotFoundException: C:\MyFolder\Test.xml (The system cannot find the file specified)
为什么不能代码打开/读取我的文件,但像记事本++其他程序可以这样做?
***注:文件的真实名称是 “使用情况\ testSuitesA_E_1002 + $ {}用户+ 3_12022016 $ {日期和时间} 2_2.5.xml”。
请修改您的代码如下:
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());
为使该代码运行,建立了项目.class
文件。类加载器需要有.class
文件。否则,将无法从classpath中读取文件夹或文件。
注意 :
新的文件( “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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句