Appending objects to a binary file
<p>Supose you have to following method:</p>

<pre><code>public static void writeToBinary(Object obj, String filename) 
{
 ObjectOutputStream oos = null;
 try {
  oos = new ObjectOutputStream(new FileOutputStream(filename));
  oos.writeObject(obj);
 } catch (Exception e) {
  e.printStackTrace();
 }  finally{
  try{
   if (oos != null) oos.close ();
  }catch (Exception e){
   e.printStackTrace();
  }
 }
}
</code></pre>

<p>As you can see, the method writes an object to a binary file.<br/><br/></p>

<p>But now you want to rewrite the same method to allow appending objects to the same file.<br/>
Ok, you look at the java documentation and you see that you have to add a parameter with value true to the FileOutputStream:<br/><br/></p>

<pre><code>oos = new ObjectOutputStream(new FileOutputStream(filename, true));
</code></pre>

<p>You compile but, whoops!, it seems that it continues overriding the file.<br/><br/>
Well, the problems begin. After searching in google you read that you have to use the <strong>SAME</strong> ObjectOutputStream to append objects to the same file. You want to have a function that every time you call it, it appends an object. I.e. : <br/></p>

<pre><code>writeToBinary("a", filename);
writeToBinary("b", filename);
</code></pre>

<p>But as I said before, you have to use the same ObjectOutputStream.</p>

<p>Solution 1:</p>

<pre><code>ObjectOutputStream out = getOutputStream (filename);
writeToBinary("a", out);
writeToBinary("b", out);
writeToBinary("c", out);
out.close ();
</code></pre>

<p>This is very ugly because I want to hide the usage of streams.<br/><br/>
<strong>Is there any other solution?</strong><br/>
<br/>
EDIT: The method is static. It is inside an utility class where all methods are static.<br/><br/>
EDIT2: SOLVED! <a href="http://stackoverflow.com/questions/1194656/appending-to-an-objectoutputstream">Appending to an ObjectOutputStream</a>. See accepted answer to my question.
Thanks.</p>
