rikojir
rikojir

Reputation: 115

Line Break in an ObjectOutputStream/ObjectInputStream in Java?

I've written a simple program to serialize and deserialize objects like books, magazines and so on into a file, and I've used the ObjectInputStream/ObjectOutputStream classes of the Java utility library.

Everything works, but I would like to add some line breaks after every object, so that it is more readable when opening the file.

Is there any aquivalent for the "\n" when using Strings in the ObjectInputStream/ObjectOutputStream classes?

PS: I've also a version where i serialize and deserialize with XStream using xml data. Has anyone an idea, if there exists also a possibility, to make such a break using XStream?

OutputStream fos = null;
    ObjectOutputStream o = null;

    // Now serialize objects into the file
    try
    {
      fos = new FileOutputStream("C:\\Users...");
// Initialize the ObjectOutputStream with XStream when xml_switcher is set to true        
      if (xml_switcher == true) {       
          o = xstream.createObjectOutputStream(fos);        
      }
// Otherwise normal serializing by creating a normal ObjectOutputStream
      else { 
          o = new ObjectOutputStream( fos );                
      }

      ArrayList<Printing> resultList = Access.getAllPrintings();
        Iterator<Printing> it = resultList.iterator();
        while (it.hasNext()) {
            if (xml_switcher == true) {
                o.writeObject(it.next());
// So here's my problem: I would like to have something like o.write("\n") 
// using XStream
            }
            else {
                o.writeObject(it.next().toString());
// Same here but without XStream
            }
        }
    }

Upvotes: 0

Views: 3553

Answers (1)

Joni
Joni

Reputation: 111389

You can inject arbitrary data into an ObjectOutputStream using the write(int) and write(byte[]) methods. Just make sure that the code reading the stream knows how to handle it. A line break in particular can be written with

out.write('\n');

That said, the object serialization format is not designed to be human readable. If you want human readable output I suggest using JSON.

Upvotes: 2

Related Questions