/* * [TestByteArrayOutputStream.java] * * Summary: Testing ByteArrayOutputStream. Demonstrates finish gotcha. * * Copyright: (c) 2011-2017 Roedy Green, Canadian Mind Products, http://mindprod.com * * Licence: This software may be copied and used freely for any purpose but military. * http://mindprod.com/contact/nonmil.html * * Requires: JDK 1.8+ * * Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/ * * Version History: * 1.0 2011-11-27 initial version */ 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. *

* 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 { // O P E N final File o = new File( "temp.ser" ); final FileOutputStream fos = new FileOutputStream( o ); final OutputStream gzos = new GZIPOutputStream( fos, 1024/* buffsize */ ); final ObjectOutputStream oos = new ObjectOutputStream( gzos ); // W R I T E oos.writeObject( new Integer( 149 ) ); // F L U S H oos.flush(); // C L O S E 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 { // O P E N final ByteArrayOutputStream baos = new ByteArrayOutputStream( 1024 ); final GZIPOutputStream gzos = new GZIPOutputStream( baos, 1024/* buffsize */ ); final ObjectOutputStream oos = new ObjectOutputStream( gzos ); // W R I T E oos.writeObject( new Integer( 149 ) ); byte[] result0 = baos.toByteArray(); out.println( "RAM result before flush " + result0.length + " oops" ); // F L U S H gzos.finish(); // necessary unless you do toByteArray() after close. oos.flush(); byte[] result1 = baos.toByteArray(); out.println( "RAM result after flush " + result1.length + " oops" ); // C L O S E oos.close(); // you don't get accurate results until AFTER the 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(); // output // file size: 94 // RAM result before flush 10 oops // RAM result after flush 10 oops // RAM result after close 94 ok } }