ByteArrayInputStream

Java ByteArrayInputStream Example

In this example we will discuss about ByteArrayInputStream class and its usage. A ByteArrayInputStream contains an internal buffer that contains bytes that may be read from the stream. An internal counter keeps track of the next byte to be supplied by the read method.

ByteArrayInputStream extends InputStream, the abstract class which is the superclass of all classes representing an input stream of bytes.

The ByteArrayInputStream class exists since JDK1.0.

The structure of ByteArrayInputStream

Constructor:

  • ByteArrayInputStream(byte[] buf)Creates a ByteArrayInputStream so that it uses buf as its buffer array.
  • ByteArrayInputStream(byte[] buf, int offset, int length)Creates ByteArrayInputStream that uses buf as its buffer array. The initial value of pos is offset and the initial value of count is the minimum of offset+length and buf.length. The buffer array is not copied. The buffer’s mark is set to the specified offset.

The ByteArrayInputStream in Java

To see a basic usage of the ByteArrayInputStream, create a class called SimpleByteArrayInputStreamExample with the following source code:

package com.javacodegeeks.examples;

import java.io.ByteArrayInputStream;
import java.util.Random;

public class SimpleByteArrayInputStreamExample {

	public static void main(String[] args) {
		byte[] buffer = new byte[10];
		Random rnd = new Random();
		
		for (int i=0;i<buffer.length;i++) {
			buffer[i] = (byte) rnd.nextInt();
		}
		
		ByteArrayInputStream b = new ByteArrayInputStream(buffer);
		
		System.out.println("All the elements in the buffer:");
		
		int num;
		while( (num = b.read()) != -1 ) {
			System.out.print(num+" ");
		}
		
	}

}

Firstly, I generated a byte array with random integers, using a Random instance. Then, on line 16, I created the ByteArrayInputStream instance, passing this byte array as argument, in order to read from that byte array. After that, I read every number inside the buffer using the read() method, which returns -1 if the end of the buffer is reached.

You can see that I didn’t call the close() method. This because closing a ByteArrayInputStream has no effect.

The output of this program is:

All the elements in the buffer:
106 249 146 242 149 74 140 72 141 48

Another usage of ByteArrayInputStream

In the above example, I used the read() to read from the ByteArrayInputStream. But there is also another implementation of the same method, the read(byte[] b, int off, int len) method. This method is used to read len bytes from the array, starting with an offset equals to off.

To see this in an example, create a class called AnotherByteArrayInputStreamExample with the following source code:

package com.javacodegeeks.examples;

import java.io.ByteArrayInputStream;

public class AnotherByteArrayInputStreamExample {
	public static void main(String[] args) {
		 byte[] buf = {1,2,3,4,5,6,7,8,9};
	     ByteArrayInputStream b = new ByteArrayInputStream(buf);
      
         byte[] newBuffer = new byte[6];
         int num = b.read(newBuffer, 2, 4);
         
         System.out.println("Bytes read: "+num);
         

         for (int i=0;i<newBuffer.length;i++) {
            int nr = (int) newBuffer[i];
            if(newBuffer[i]==0)
               System.out.print("-null- ");
            else
               System.out.print(nr+" ");
         }
			
	}
}

Using the b.read(newBuffer, 2, 4); method on line 11, we put 4 first elements of the ByteArrayInputStream instance b to the newBuffer array, starting at the position with index 2. This is why the two first indexes will be null.

Running this example gives this output:

Bytes read: 4
-null- -null- 1 2 3 4 

A better usage of ByteArrayInputStream

Another simple usage of ByteArrayInputStream would be a way of capitalizing the input from the user. To do this, create a class called Capitalizer and put this code into it:

package com.javacodegeeks.examples;

import java.io.ByteArrayInputStream;
import java.util.Scanner;

public class Capitalizer {

	public static void main(String[] args) {
		Scanner stdIn = new Scanner(System.in);
		
		System.out.print("Enter a string: ");
		String message = stdIn.nextLine();
		StringBuilder sb = new StringBuilder();
		
		ByteArrayInputStream str = new ByteArrayInputStream(message.getBytes());
		
		int ch;
		while ( (ch = str.read()) != -1) {
			sb.append(Character.toUpperCase((char) ch));
		}
		System.out.println("Your capitalized message: "+sb.toString());

	}

}

This class gets the bytes of a string, and then executes toUpperCase() for each of the bytes, using a ByteArrayInputStream to read every byte.

A sample output would be:

Enter a string: Hello, Java Code Geeks!
Your capitalized message: HELLO, JAVA CODE GEEKS!

More about the ByteArrayInputStream in Java

A ByteArrayInputStream contains an internal buffer that contains bytes that may be read from the stream. An internal counter keeps track of the next byte to be supplied by the read method.

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

Download Code

Download
You can download the full source code of this example here : ByteArrayInputStreamExample

Aldo Ziflaj

Aldo is a student of Computer Engineering and a programming addict. He spares his free time coding, whether mobile, web, or desktop programming. He is also one of the co-founders of Things Lab.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button