即使我为它生成 jar 文件,我在哪里可以放置 XML 文件以使程序能够访问它?
当我将 XML 文件放入项目文件时,程序成功运行为以下代码:
public class one {
public final static void main(String[] args) throws Exception {
FileInputStream file = new java.io.FileInputStream("document.xml");//i put document.xml in project file
javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();
dbf.setCoalescing(true);
javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
org.w3c.dom.Document doc = db.parse(file);
one obj = new one ();
obj.changeValue(doc, "192837465", "192837465");
obj.save("document.xml",doc);
}
public void changeValue(org.w3c.dom.Document doc, String oldValue, String NewValue) throws Exception{
org.w3c.dom.Element root = doc.getDocumentElement();
org.w3c.dom.NodeList childNodes = root.getElementsByTagName("Employee");
for (int i = 0; i < childNodes.getLength(); i++) {
org.w3c.dom.NodeList subChildNodes = childNodes.item(i).getChildNodes();
for (int j = 0; j < subChildNodes.getLength(); j++) {
try {
if (subChildNodes.item(j).getTextContent().equals(oldValue)) {
subChildNodes.item(j).setTextContent(NewValue);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public void save(String url ,org.w3c.dom.Document doc) throws Exception {
javax.xml.transform.TransformerFactory factory1 = javax.xml.transform.TransformerFactory.newInstance();
javax.xml.transform.Transformer transformer = factory1.newTransformer();
transformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes");
java.io.StringWriter writer = new java.io.StringWriter();
javax.xml.transform.stream.StreamResult result = new javax.xml.transform.stream.StreamResult(writer);
javax.xml.transform.dom.DOMSource source = new javax.xml.transform.dom.DOMSource(doc);
transformer.transform(source, result);
String s = writer.toString();
System.out.println(s);
java.io.FileWriter fileWriter = new java.io.FileWriter(url);
java.io.BufferedWriter bufferedWriter = new java.io.BufferedWriter(fileWriter);
bufferedWriter.write(s);
bufferedWriter.flush();
bufferedWriter.close();
}
}
但是当我使用 eclipse 在 jar 文件中制作程序并使用以下命令从命令提示符运行文件时:
java -jar xml.jar
它给了我这个例外:
Exception in thread "main" java.io.FileNotFoundException: document.xml (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at one.main(one.java:13)
为什么会出现这个错误以及如何纠正它?