我創建了一個簡單的類來創建XML文檔。 但是,如果我叫一次創建文件時不會覆蓋同名的文件的方法了。 我如何才能讓這個類自動覆蓋現有的同名文件? 與Java流結果覆蓋文件
import java.io.File;import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document; import org.w3c.dom.Element;
public class XMLCreater { public static void CreateXMLDoc(String name, String root, String[] elements, String[] children) throws TransformerConfigurationException { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement(root); doc.appendChild(rootElement);
for (int i = 0; i < elements.length; i ++) { Element element = doc.createElement(elements[i]); element.appendChild(doc.createTextNode(children[i])); rootElement.appendChild(element); } TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); File dir = new File(System.getProperty("user.dir")); StreamResult result = new StreamResult(new File(dir + "\\XML\\" + name + ".xml")); transformer.transform(source, result); } catch(ParserConfigurationException pce){ pce.printStackTrace(); } catch(TransformerException tfe) { tfe.printStackTrace(); } }
}
會發生什麼代替?什麼是Java版本? – BalusC 2011-02-08 19:13:05