Java - ByteArrayInputStream and ByteArrayOutputStream example

Posted on November 5, 2016


The ByteArrayInputStream and ByteArrayOutputStream read data from and write data to a byte array in memory, respectively.

Here is an example to demonstrate ByteArrayInputStream.

ByteArrayInputStreamExample.java

package com.boraji.tutorial.io;

import java.io.ByteArrayInputStream;

/**
 * @author imssbora
 * ByteArrayInputStreamExample.java
 * Nov 5, 2016
 */
public class ByteArrayInputStreamExample {
	public static void main(String[] args) {
		String data="This is an example of ByteArrayInputStream";
		
		ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(data.getBytes());
		int d;
		while((d=byteArrayInputStream.read())!=-1){
			System.out.print((char)d);
		}	
	}
}

Output

This is an example of ByteArrayInputStream 

 

Following is an example to demonstrate ByteArrayOutputStream.

ByteArrayOutputStreamExample.java

package com.boraji.tutorial.io;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @author imssbora 
 * ByteArrayOutputStreamExample.java 
 * Nov 5, 2016
 */
public class ByteArrayOutputStreamExample {
	public static void main(String[] args) throws IOException {
		String string1 = "This is an example ";
		String string2 = "of ByteArrayInputStreamExample";

		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		byteArrayOutputStream.write(string1.getBytes());
		byteArrayOutputStream.write(string2.getBytes());

		System.out.println("Output data : " + byteArrayOutputStream.toString());
	}
}

Output

Output data : This is an example of ByteArrayOutputStream

Note - Closing a ByteArrayOutputStream has no effect. The methods in this class can be called after the stream has been closed without generating an IOException.