從哪裏可以放置XML文件以使程序能夠訪問它,即使我爲它生成了jar文件?從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)
爲什麼這個錯誤以及如何糾正它?
感謝您的回答。它工作在日食正常,但當我做的jar文件它給了我同樣的錯誤,我說 – 2013-02-26 14:39:06