Java用流结果覆盖文件

时间:2011-02-08 18:37:45

标签: java xml file stream overwrite

我创建了一个简单的类来创建XML文档。 但是,如果在创建同名文档时多次调用该方法,则文件不会覆盖。 如何让类自动覆盖同名的现有文件?

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(); } }

}

2 个答案:

答案 0 :(得分:1)

我使用以下语句执行了您的代码:

public static void main (String[] args) 
{
    XMLCreater x = new XMLCreater();
    String[] s = {"A","B","C"};
    try 
    {
        x.CreateXMLDoc("k","root",s,s);
        x.CreateXMLDoc("k","root",s,s);
        x.CreateXMLDoc("fakih","root",s,s);
    }
    catch (TransformerConfigurationException exception) 
    { exception.printStackTrace(); }
}

它很好地覆盖了现有文件,没有覆盖问题,请自行检查。

答案 1 :(得分:1)

我在这里说实话......我无法复制你的问题。当我在for循环中多次运行此程序时,它对我来说很好。在运行程序之前,您确定没有意外打开结果文件,从而将其锁定吗?

如果您担心多个线程同时运行程序,也许您可​​以应用synchronized块来阻止两个线程尝试编写同一个文件,如下所示: -

...

synchronized (XMLCreater.class) {
    StreamResult result = new StreamResult(new File(dir + "\\XML\\" + name + ".xml"));
    transformer.transform(source, result);
}