使用XStream将Java对象序列化为XML

使用XStream将Java对象序列化为XML

问题描述:

问题在于每次执行main方法时,a.xml的旧内容都会丢失并被替换为新内容。如何在不丢失先前信息的情况下将内容附加到a.xml文件?

The problem is that every time I execute the main method, the old content of a.xml is lost and is substituted with a new one. How to append content to the a.xml file without losing the previous information?

import java.io.FileNotFoundException;
import java.io.PrintWriter;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;


public class Test {
    public static void main(String[] args) throws FileNotFoundException {
        XStream xs = new XStream(new DomDriver());
        Foo f = new Foo(1, "booo", new Bar(42));
        PrintWriter pw = new PrintWriter("a.xml");
        xs.toXML(f,pw);
    }
}


public class Bar {
    public int id;

    public Bar(int id) {
        this.id = id;
    }

}


public class Foo {
    public int a;
    public String b;
    public Bar boo;
    public Foo(int a, String b, Bar c) {
        this.a = a;
        this.b = b;
        this.boo = c;
    }
}


示例代码

public static void main(String a[]){
  //Other code omitted
  FileOutputStream fos = new FileOutputStream("c:\\yourfile",true); //true specifies append
  Foo f = new Foo(1, "booo", new Bar(42));
  xs.toXML(f,fos);
}