这是我的代码。
File file = new File("src/qrcodescanner/xmlpac/"+filename);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
document = db.parse(file);
document.getDocumentElement().normalize();
答案 0 :(得分:1)
如果它不是红色的,那么它很可能不是你期望的那样。根据您发布的代码判断,我认为您的xml文件旨在驻留在jar / package结构中。
这是我的测试项目结构:
src
|-- main
|-- java
|-- mypackage
MyCode.java
MyResource.xml
相应生成的jar文件位于target/
目录,如下所示:
mypackage
MyCode.class
MyResource.xml
MyResource.xml
看起来像这样:
<a>b</a>
MyCode.java
看起来像这样:
public class MyCode {
public static void main(String[] args) throws Exception {
String packagePath= "/mypackage/MyResource.xml";
String myPath ="src/main/java"+packagePath;
File f = new File(myPath);
System.out.println(f.exists());
InputStream is = Class.class.getResourceAsStream(packagePath);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document d = db.parse(is);
System.out.println(d.getElementsByTagName("a").item(0).getTextContent());
}
}
运行时打印:
true
b
方法getResourceAsStream用于从JAR内部加载资源。希望有所帮助。