Topics Index

ByteArrayOutputStreamDemo - Java Example Program


class ByteArrayOutputStreamDemo
    public static void main(String arg[])
        ByteArrayOutputStream baos = new ByteArrayOutputStream(); // LINE A
        String lowerCase = "merit campus";
        byte b[] = lowerCase.getBytes();
        baos.write(b); // LINE B
        System.out.println("Converting to String : ");
        // using toString
        String upperCase = baos.toString().toUpperCase(); // LINE C
        System.out.println("Converting to byte array : ");
        // using toByteArray
        byte b1[] = baos.toByteArray(); // LINE D
        for(int i = 0; i < b1.length; i++)
            System.out.print((char) b1[i]);
        baos.close(); // LINE E
        baos.reset(); // LINE F
        String afterReset = baos.toString();
        System.out.println("After Reset : " + afterReset);    


At LINE A we created a ByteArrayOutputStream object.
At LINE B we are writing the bytes of array b into baos.
At LINE C we are converting the byte array inside baos to string and then to uppercase.
At LINE D we are now changing the stream back to byte array.
At LINE E we are closing the stream which doesn't show any effect.
At LINE F we are clearing the buffer using reset method. After reset there will be no bytes in stream.

  • Take a String I LOVE JAVA convert it to byte array and write it to ByteArrayOutputStream.
  • Now convert it back to string.

© meritcampus 2019

All Rights Reserved.

Open In App