< Prev
Next >



ByteArrayInputStream



ByteArrayInputStream class is a subclass of InputStream abstract class. It creates an inputstream, which is used to read byte/bytes from its own internal buffer, which is initialized using a byte array.




Constructor :


ByteArrayInputStream(byte[] buf)
This is the most used constructor and it creates a ByteArrayInputStream object with its own internal buffer initialized to the value of a byte array, which is passed to this constructor as a parameter.
Example-:
String str = "Learning about Input Streams";
byte[] b= str.getBytes();
ByteArrayInputStream bais= new ByteArrayInputStream(b); 
Here, we have a byte array b, which is initialized to the value of a String, str. We have created a ByteArrayInputStream object with its own buffer initialized to the value of this byte array b.




Some Methods for reading ByteArrayInputStream


Access modifier of these methods is public.

Methods Description
available()
This method gives the remaining number of bytes available to read from this input stream.

read()
This method reads one byte at a time from this input stream.

read(byte[])
This method reads a whole byte array at a time from this input stream.

close()
This method closes this input stream and also frees any resources connected with this input stream.






Reading one byte at a time out of a byte array using read() method.


In the next code, we have initialized the internal buffer of ByteArrayInputStream to the value of a byte array, which is initialized using a String.
// A program to read one byte at a time from a byte array using ByteArrayInputStream's internal buffer.

import java.io.*;

class A
{
public static void main(String... ar)
{
String str= new String("World peace is extremely important");
byte b[]=str.getBytes();
try
{
ByteArrayInputStream bais= new ByteArrayInputStream(b); 
System.out.println("Number of bytes available to read = " + bais.available());

int c;
while( (c=bais.read())!=-1) //reading a byte at a time out of ByteArrayInput's buffer
System.out.print((char)c);

bais.close();
}
catch(IOException e)
{
System.out.println(e);
}

}
}


Output is -:


Number of bytes available to read = 34
World peace is extremely important


Program Analysis






Note

Even after closing the stream by calling close(), we can still read the bytes out of buffer of ByteArrayInputStream and no IOException will be thrown.



Please share this article -





< Prev
Next >
< File Output Stream
ByteArrayOutputStream>
Please subscribe our social media channels for notifications, we post a new article everyday.

Decodejava Google+ Page Decodejava Facebook Page  DecodeJava Twitter Page

Coming Next
-
C++ and Python

Ad2