ByteArrayOutputStream In Java Example

Chapter: Java I/O Last Updated: 21-07-2016 17:18:23 UTC

Program:

            /* ............... START ............... */
                
import java.io.ByteArrayOutputStream;

public class JavaByteArrayOutputStream {

	public static void main(String[] args) {

		try {

			ByteArrayOutputStream byteStream = new ByteArrayOutputStream();

			for (byte i = 0; i < 5; i++) {
				byteStream.write(i);
			}
			byteStream.close();

			System.out.println("byteStream.size(): " + byteStream.size());

			byte[] array = byteStream.toByteArray();
			for (byte b : array) {
				System.out.print(b);
			}

		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}
	}
}
                /* ............... END ............... */
        

Output

byteStream.size(): 5
01234

Notes:

  • The ByteArrayOutputStream class stream creates a buffer in memory and all the data sent to the stream is stored in the buffer.
  • ByteArrayOutputStream() - constructor creates a ByteArrayOutputStream having buffer of 32 byte.
  • ByteArrayOutputStream(int a) - constructor creates a ByteArrayOutputStream having buffer of the given size.

Tags

ByteArrayInputStream, Java, Java I/O

Similar Programs Chapter Last Updated
Hidden File Check In Java Example Java I/O 20-06-2016
FileWriter In Java Example Java I/O 21-07-2016
FileReader In Java Example Java I/O 21-07-2016
FileOutputStream In Java Example Java I/O 21-07-2016
FileInputStream In Java Example Java I/O 21-07-2016
DataOutputStream In Java Example Java I/O 21-07-2016
DataInputStream In Java Example Java I/O 21-07-2016
CharArrayWriter In Java Example Java I/O 13-04-2016
CharArrayReader In Java Example Java I/O 21-07-2016
ByteArrayInputStream In Java Example Java I/O 21-07-2016
BufferedWriter In Java Example Java I/O 21-07-2016
BufferedReader In Java Example Java I/O 21-07-2016
BufferedOutputStream In Java Example Java I/O 21-07-2016
BufferedInputStream In Java Example Java I/O 21-07-2016
ProcessBuilder To Make System Calls In Java Java I/O 19-08-2017

1