package basics.filesystem.file;

import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import basics.unexpected.Failure;

public class ObjectInputStreamWrapper
{
private File              _file;
private FileInputStream   _fileInputStream;
private ObjectInputStream _objectInputStream;

/**
 * @param file must not be <code>null</code>.
 */
public ObjectInputStreamWrapper(File file)
{
   if(file == null) throw new Failure("Input file is null!");
   try
   {
      _file = new File(file.getPath());
      _fileInputStream = new FileInputStream(_file);
      _objectInputStream = new ObjectInputStream(_fileInputStream);
   }
   catch(EOFException e)
   {
      close();
   }
   catch(IOException e)
   {
      close();
      throw new Failure(e);
   }
}

/**
 * Checks if file length is > 0 and the number of available bytes from the file input stream is > 0.
 */
public boolean isAvailable()
{
   try
   {
      return _file.length() > 0 && _fileInputStream.available() > 0;
   }
   catch(Exception e)
   {
      return false;
   }
}

/**
 * Retreives the next object from the objectinputstream.
 * @return the next object, may be <code>null</code>.
 */
public Object readObject() 
{
   Object result = null;
   try
   {
      if(_fileInputStream.available() > 0)
         result = _objectInputStream.readObject();
   }
   catch(Exception e)
   {
   }
   return result;
}

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

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