package com.mindprod.example;
import org.apache.commons.io.output.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.zip.GZIPOutputStream;
import static java.lang.System.*;
/**
* Testing ByteArrayOutputStream. Demonstrates finish gotcha.
* <p/>
* You must do a close() before the toByteArray or use finish.
* Also shows how to construct complex byte arrays.
*
* @author Roedy Green, Canadian Mind Products
* @version 1.0 2011-11-27 initial version
* @since 2011-11-27
*/
public final class TestByteArrayOutputStream
{
/**
* write an integer object to a file in compressed format
*
* @throws IOException if cannot write file
*/
private static void writeToFile() throws IOException
{
final File o = new File( "temp.ser" );
final FileOutputStream fos = new FileOutputStream( o );
final OutputStream gzos = new GZIPOutputStream( fos, 1024);
final ObjectOutputStream oos = new ObjectOutputStream( gzos );
oos.writeObject( new Integer( 149 ) );
oos.flush();
oos.close();
out.println( "file size: " + o.length() );
}
/**
* write an integer object to a buffer in RAM in compressed format
*
* @throws IOException if cannot write file
*/
private static void writeToRAM() throws IOException
{
final ByteArrayOutputStream baos = new ByteArrayOutputStream( 1024 );
final GZIPOutputStream gzos = new GZIPOutputStream( baos, 1024);
final ObjectOutputStream oos = new ObjectOutputStream( gzos );
oos.writeObject( new Integer( 149 ) );
byte[] result0 = baos.toByteArray();
out.println( "RAM result before flush " + result0.length + " oops" );
gzos.finish();
oos.flush();
byte[] result1 = baos.toByteArray();
out.println( "RAM result after flush " + result1.length + " oops" );
oos.close();
byte[] result2 = baos.toByteArray();
out.println( "RAM result after close " + result2.length + " ok" );
}
/**
* Testing ByteArrayOutputStream
*
* @param args not used
*/
public static void main( String[] args ) throws IOException
{
writeToFile();
writeToRAM();
}
}