使用XStream将Java对象序列化为XML [英] Serializing Java objects to XML with XStream

查看:116
本文介绍了使用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);
}

这篇关于使用XStream将Java对象序列化为XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆