Advertisement
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-:
|
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 number of bytes from the input stream and stores them into its buffer array. |
close() | This method closes this input stream and also frees any resources connected with this input stream. |
Advertisement
// Java - A program to read one byte at a time from a byte array by using ByteArrayInputStream's internal buffer.
import java.io.*;
class A
{
public static void main(String... ar)
{
//Creating a String
String str= new String("World peace is extremely important");
//Creating a byte array from a String
byte b[]=str.getBytes();
try
{
//Creating a ByteArrayInputStream object from a byte array
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);
//Closing the ByteArrayInputStream
bais.close();
}
catch(IOException e)
{
System.out.println(e);
}
}
}
Number of bytes available to read = 34
World peace is extremely important
// Java - A program to read a whole byte array at once by using ByteArrayInputStream's internal buffer.
import java.io.*;
public class A
{
public static void main(String... ar)
{
//Creating a String
String str= new String("World peace is extremely important");
//Creating a byte array from a String
byte b1[]=str.getBytes();
try
{
//Creating a ByteArrayInputStream object from a byte array
ByteArrayInputStream bais= new ByteArrayInputStream(b1);
System.out.println("Number of bytes available to read = " + bais.available());
//Creating a new byte array, which will be filled by reading ByteArrayInputStream.
byte b2[]= new byte[bais.available()];
int c;
//reading a whole byte array at once, by calling read(byte[]) method of ByteArrayInputStream
if( (c=bais.read(b2))!=-1) //This read() method stops reading from file when EOF is reached i.e. -1
System.out.print("Number of bytes just read = " +c);
//Creating a new String from the byte array
String s= new String(b2);
//Printing the data just read by ByteArrayInputStream
System.out.println("\nContent just read by ByteArrayInputStream: " + s);
//Closing the ByteArrayInputStream
bais.close();
}
catch(IOException e)
{
System.out.println(e);
}
}
}
Number of bytes available to read = 34
Number of bytes just read = 34
Content just read by ByteArrayInputStream: World peace is extremely important
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement