Java overwriting files with stream result
I created a simple class to create an XML document. However, if I call the method more than once while creating a document of the same name the file does not overwrite. How could I make the class automatically overwrite existing files of the same name?
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(); } }
}
I executed your code with the following statements:
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(); }
}
And it nicely overwrites the existing files, no problems about overwriting, check it yourself.
I'll be honest here... I'm not able to replicate your problem. It works fine for me when I run this program multiple times in a for loop. Are you sure you didn't accidentally open the result file, thus locking it, before running your program?
If you are concerned of having multiple threads running your program at the same time, perhaps you can apply a synchronized
block to prevent two threads trying to write the same file, like this:-
...
synchronized (XMLCreater.class) {
StreamResult result = new StreamResult(new File(dir + "XML" + name + ".xml"));
transformer.transform(source, result);
}
链接地址: http://www.djcxy.com/p/34936.html
下一篇: Java用流结果覆盖文件