我正在使用下面的代码。但是,当我运行代码时,我想将新XML附加到相同的TXT文件中。可以使用JDOM。请帮助我..
xmlOutput.output(doc,new FileWriter(“c:\ updated.txt”));是需要修改的吗?
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
public class Replacer {
public static void main(String[] args) {
try {
SAXBuilder builder = new SAXBuilder();
File xmlFile = new File("c:\\file.xml");
String temp = "1234567";
Document doc = (Document) builder.build(xmlFile);
Element rootNode = doc.getRootElement();
System.out.println("Root Node is --> "+rootNode);
Element ShipmentLines = rootNode.getChild("ShipmentLines");
Element ShipmentLine = ShipmentLines.getChild("ShipmentLine");
Element Containers = rootNode.getChild("Containers");
Element Container = Containers.getChild("Container");
ShipmentLine.getAttribute("OrderNo").setValue(temp);
Container.getAttribute("ContainerScm").setValue(temp);
XMLOutputter xmlOutput = new XMLOutputter();
xmlOutput.setFormat(Format.getPrettyFormat());
xmlOutput.output(doc, new FileWriter("c:\\updated.txt"));
} catch (IOException io) {
io.printStackTrace();
} catch (JDOMException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:1)
JDOM不直接支持附加到现有文件,但它只需要少量额外代码。只需将输出写入StringWriter,获取字符串,然后将字符串附加到现有文件。一种可能的实现方式:
XMLOutputter xmlOutput = new XMLOutputter();
xmlOutput.setFormat(Format.getPrettyFormat());
StringWriter out = new StringWriter();
xmlOutput.output(doc, out);
FileUtils.writeStringToFile(new File("c:\\updated.txt"), out.toString(), true);
我在这里使用commons-io FileUtils类作弊。看到 Append data into a file using Apache Commons I/O
如果commons-io对您的应用程序不可用或不实用,那么请编写您自己的append-string-to-file方法。