package basics.filesystem.file;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import basics.unexpected.Failure;

public class ObjectOutputStreamWrapper
{
private final File         _file;
private ObjectOutputStream _objectOutputStream;
private FileOutputStream   _fileOutputStream;

/**
 * @param file must not be <code>null</code>.
 */
public ObjectOutputStreamWrapper(File file)
{
   if(file == null) throw new Failure("Ouput file is null!");
   try
   {
      _file = new File(file.getPath());
      _fileOutputStream = new FileOutputStream(_file, false);
      _objectOutputStream = new ObjectOutputStream(_fileOutputStream);
   }
   catch(IOException e)
   {
      close();
      throw new Failure(e);
   }
}

/**
 * Writes the given object to the objectoutputstream.
 */
public void writeObject(Object o)
{
   if(o == null) throw new Failure("the given object must not be null");
   try
   {
      _objectOutputStream.writeObject(o);
   }
   catch(IOException e)
   {
      FileUtl.silentClose(_fileOutputStream);
      FileUtl.silentClose(_objectOutputStream);
      throw new Failure(e);
   }
}

public void reset()
{
   try
   {
      _objectOutputStream.reset();
   }
   catch(IOException e)
   {
      close();
      throw new Failure(e);
   }
}

/**
 * Closes all streams.
 */
public void close()
{
   FileUtl.silentClose(_fileOutputStream);
   FileUtl.silentClose(_objectOutputStream);
}

/**
 * Conveniance method in case that {@link #close} was not called.<br />
 * Attempts to close all streams.
 */
protected void finalize() throws Throwable
{
   super.finalize();
   close();
}
}
