我正在尝试操作名为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)为什么代码不能打开/读取我的文件,但是像Notepad++这样的其他程序可以这样做?
*注意:文件的真实名称是"Use-cases\testSuitesA_E_1002+${user}3_12022016+${date}2_2.5.xml".
发布于 2019-03-07 06:58:12
请修改您的代码如下:
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 ClassLoader需要有文件。否则,它将无法从类路径.读取文件夹或文件。
注:
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)发布于 2019-03-04 12:18:55
试试Document doc = builder.parse(new File("Use-cases\\testSuitesA_E_1002+${user}3_12022016+${date}2_2.5.xml"))怎么样?
在您的文件路径中,用例\testSuitesA_E_1002+${user}3_12022016+${date}2_2.5.xml \t表示转义序列。
另外,我想检查一下您正在使用的{date},也许您的约会被格式化为06\06\2018?
发布于 2019-03-07 16:39:54
<?xml version="1.0" encoding="UTF-8"?>
<company>
<staff id="100">
<firstname>Tom</firstname>
<lastname>Jerry</lastname>
<nickname>Tomy</nickname>
<salary>100000</salary>
</staff>
<staff id="200">
<firstname>Micky</firstname>
<lastname>Mouse</lastname>
<nickname>Mike</nickname>
<salary>200000</salary>
</staff>
</company>
https://stackoverflow.com/questions/54929686
复制相似问题