gpt4 book ai didi

Java 用流结果覆盖文件

转载 作者:行者123 更新时间:2023-11-30 05:06:32 25 4
gpt4 key购买 nike

我创建了一个简单的类来创建 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();
}
}

}

最佳答案

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

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

而且它很好地覆盖了现有的文件,覆盖没有问题,你自己检查一下。

关于Java 用流结果覆盖文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4936931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com