views:

92

answers:

3

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;
    }
}
A: 

Use a FileWriter instead of a PrintWriter

Quotidian
Thanks, but it still doesn't work as I want it to.
brain_damage
+2  A: 

Sample Code

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);
}
chedine
Thank you very much :)
brain_damage
+1  A: 

The question is, do you really want to append the serialized XML string to the file or do you want to add the new Foo instance to the XML structure.

Appending on a string basis would result in invalid XML about like this:

<foo>
  <a>1</a>
  <b>booo</b>
  <bar>
    <id>42</id>
  </bar>
</foo>
<foo>
  <a>1</a>
  <b>booo</b>
  <bar>
    <id>42</id>
  </bar>
</foo>

Instead you may want to preserve the data in a.xml by parsing it first, then add the new element and serialize the whole collection/array.

So something like this (assuming there is already a collection of Foos in a.xml):

List foos = xs.fromXml(...);
foos.add(new Foo(1, "booo", new Bar(42)));
xs.toXml(foos, pw);

... which gives you something along the lines of this:

<foos>
  <foo>
    <a>1</a>
    <b>booo</b>
    <bar>
      <id>42</id>
    </bar>
  </foo>
  <foo>
    <a>1</a>
    <b>booo</b>
    <bar>
      <id>42</id>
    </bar>
  </foo>
</foos>

HTH

Martin Klinke
Yes, that's just what I want to do. But what if the file is empty? Then List foos = xs.fromXML(...) won't be valid :?
brain_damage
You'll have to handle some special cases, that's true. But depending on XStream you will either get an exception or null, which you can then catch or check and proceed from there.
Martin Klinke
Thanks, Martin :)
brain_damage
You're welcome. Good luck with the rest ;)
Martin Klinke