Question

Is there any way to use ObjectOutputStream like this:

<tag>output of the ObjectOutputStream</tag>

If I try:

FileOutputStream fos = new FileOutputStream(filename);
ObjectOutputStream oos = new ObjectOutputStream(fos);
FileWriter fw = new FileWriter(fos);

And for example:

fw.write("<tag>");
oos.write(cool_object);
fw.wrote("</tag>");

I don't get that result. It seems the ObjectOutputStream overwrites the file completly each and every time.

Was it helpful?

Solution

try the following binary output.

oos.writeObject("<tag>");
oos.writeObject(cool_object);
oos.writeObject("</tag>");

OR text output

fw.write("<tag>"+cool_object+"</tag>");

EDIT: You may need to encode the output of cool_object.toString() if it contains and HTML special characters.

OTHER TIPS

No - a FileWriter is for writing text, but the output of ObjectOutputStream is inherently binary data. If you want to serialize objects to XML, use a serializer which knows about XML, e.g. XStream.

The ObjectOutputStream makes a binary representation. So you must first turn that into a string representation - either hex or Base64

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
String str = Base64.encodeBase64(baos.toByteArray());

then write this str between the tags.

If you want an xml representation, rather than a binary representation, then you can use the XMLEncoder which is the xml version of ObjectOutputStream

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top