Tutorial List
Home
Interview Questions
Interview
Interview Questions
Links
Web Home
About Us

ByteArrayOutputStream


The ByteArrayOutputStream: class stream creates a buffer in memory and all the data sent to the stream is stored in the buffer. There are following forms of constructors to create ByteArrayOutputStream objects
Following constructor creates a buffer of 32 byte:
OutputStream bOut = new ByteArrayOutputStream()
Following constructor creates a buffer of size int a:
OutputStrem bOut = new ByteArrayOutputStream(int a)
Once you have ByteArrayOutputStream object in hand then there is a list of helper methods which can be used to write the stream or to do other operations on the stream.
SNMethods with Description
1public void reset()
This method resets the number of valid bytes of the byte array output stream to zero, so all the accumulated output in the stream will be discarded.
2public byte[] toByteArray()
This method creates a newly allocated Byte array. Its size would be the current size of the output stream and the contents of the buffer will be copied into it. Returns the current contents of the output stream as a byte array.
3public String toString()
Converts the buffer content into a string. Translation will be done according to the default character encoding. Returns the String translated from the buffer.s content.
4public void write(int w)
Writes the specified array to the output stream.
5public void write(byte []b, int of, int len)
Writes len number of bytes starting from offset off to the stream.
6public void writeTo(OutputStream outSt)
Writes the entire content of this Stream to the specified stream argument.

Example:

Following is the example to demonstrate ByteArrayOutputStream and ByteArrayOutputStream
import java.io.*;

class ByteStreamTest{

   public static void main(String args[])throws IOException{

      ByteArrayOutputStream bOutput = new ByteArrayOutputStream(12);

      while( bOutput.size()!= 10 ){
         // Gets the inputs from the user
         bOutput.write(System.in.read()); 
      }

      byte b [] = bOutput.toByteArray();
      System.out.println("Print the content");
      for(int x= 0 ; x < b.length; x++){
         //printing the characters
         System.out.print((char)b[x]  + "   "); 
      }
      System.out.println("   ");

      int c;

      ByteArrayOutputStream bInput = new ByteArrayOutputStream(b);

      System.out.println("Converting characters to Upper case " );
      for(int y = 0 ; y < 1; y++ ){
         while(( c= bInput.read())!= -1){
            System.out.println(Character.toUpperCase((char)c));
         }
         bInput.reset(); 
      }
   }
}
Here is the sample run of the above program:
asdfghjkly
Print the content
a   s   d   f   g   h   j   k   l   y
Converting characters to Upper case
A
S
D
F
G
H
J
K
L
Y

No comments: