1

这是我的代码:

Element FICHADAS = new Element("FICHADAS");
Document doc = new Document(FICHADAS);
try{

    Element fichada = new Element("fichada");
    //Nº TERMINAL
    fichada.addContent(new Element("N_Terminal").setText(props.getProperty("N_TERMINAL")));
    //TARJETA
    fichada.addContent(new Element("Tarjeta").setText(codOperario));
    //FECHA
    Date fechaFormatoFecha = new Date( );
    fichada.addContent(new Element("Fecha").setText(formatoFecha.format(fechaFormatoFecha)));
    //HORA
    Date fechaFormatoHora = new Date( );
    fichada.addContent(new Element("Hora").setText(formatoHora.format(fechaFormatoHora)));
    //CAUSA
    fichada.addContent(new Element("Causa").setText("2"));
    doc.getRootElement().addContent(fichada);
    XMLOutputter xmlOutput = new XMLOutputter();
    xmlOutput.setFormat(Format.getPrettyFormat());
    xmlOutput.output(doc, new FileWriter("fichadas.xml"));

} catch(IOException io){
}

每次执行程序时,我都会创建一个新文档,如果不存在,我只想创建它,如果文档存在,只需添加内容。

4

2 回答 2

4

我认为这就是你想要做的。刚刚给出了一个伪代码:

File f = new File("fichadas.xml");
if(f.exists()){
//open file and write in it
} 
else{
//create new file
}
于 2015-04-24T08:44:58.310 回答
3

看看这个构造函数Filewriter

在给定文件名的情况下构造一个 FileWriter 对象,该对象带有一个布尔值,指示是否附加写入的数据。

同样首先您必须检查文件是否存在:

File fichadas=new File("fichadas.xml");
if (fichadas.exists()){
     // append
     xmlOutput.output(doc, new FileWriter("fichadas.xml", true));
} else {
     // create 
     xmlOutput.output(doc, new FileWriter("fichadas.xml"));
}

UPDATE以避免声明,您必须使用Format.setOmitDeclaration(boolean). 因此,您必须将格式添加到XMLOutputter

// declare XMLOutputter 
XMLOutputter xmlOutput = new XMLOutputter();

// declare Format
Format fmt = Format.getPrettyFormat();

// set omit declaration to true
fmt.setOmitDeclaration(true);

// assign Format to XMLOutputter 
xmlOutput.setFormat(fmt);
于 2015-04-24T08:44:36.647 回答