Menu
Topics Index
...
`

ByteArrayInputStreamDemo - Java Example Program


ByteArrayInputStreamDemo
import java.io.*;

class ByteArrayInputStreamDemo
{
    public static void main(String arg[])
    {
        String s = "I-LOVE-JAVA";
        byte b[] = s.getBytes();
        ByteArrayInputStream bais = new ByteArrayInputStream(b); // LINE A
        System.out.println("Available Bytes : " + bais.available()); // LINE B
        System.out.println("MarksSupported : " + bais.markSupported()); // LINE C
        //reading bytes from bais
        System.out.print((char)bais.read());
        System.out.print((char)bais.read());
        //marking the position
        bais.mark(1); // LINE D
        System.out.print((char)bais.read());
        System.out.print((char)bais.read());
        System.out.println((char)bais.read());
        //closing ByteArrayInputStream
        bais.close(); // LINE E
        //reset invoked
        System.out.println("Reset method invoked.");
        bais.reset(); // LINE F
        int c = 0;
        while((c = bais.read()) != -1)
        System.out.print((char) c);
    
    }
}
OUTPUT

Available Bytes : 11
MarksSupported : true
I-LOV
Reset method invoked.
LOVE-JAVA

DESCRIPTION

In the above program we have created a string I LOVE JAVA and change to byte array using getBytes() method.
At LINE Awe created a ByteArrayInputStream object and passed byte array b. At LINE B we are checking the available bytes in b. At LINE C we are checking whether bais is markSupported. At LINE D we marked a position in bais and set number of characters to be remembered. At LINE E we are closing the stream which doesn't show any effect. At LINE F we are invoking the reset method which will reset bytes to the mark position.

THINGS TO TRY
  • Comment LINE D and see the output. The reset method resets bytes to the starting position of the byte array.
  • Remember the close method will not show any effect on ByteArrayInputStrem.Comment LINE E and you will find no difference in output.

© meritcampus 2019

All Rights Reserved.

Open In App