java tutorial - Java - Constructors and methods of the ByteArrayOutputStream class - java programming - learn java - java basics - java for beginners



A stream of the ByteArrayOutputStream class creates a buffer in memory.

Constructors

Below is a list of constructors provided by the ByteArrayOutputStream class.

NoMethod and description
1 ByteArrayOutputStream ()
The constructor creates a ByteArrayOutputStream with a buffer size of 32 bytes.
2 ByteArrayOutputStream (int a)
The constructor creates a ByteArrayOutputStream with a buffer of the specified size.

Methods

If you use a ByteArrayOutputStream object, then you always have a list of helper methods that you can use to write the stream or perform other operations on the stream.

NoMethod and description
1 public void reset ()
The method resets the number of valid bytes in the output stream of the byte array to zero, so all gathered output will be reset.
2 public byte [] toByteArray ()
The method creates a newly allocated byte array. Its size will be the current size of the output stream, and the contents of the buffer will be copied to it. Returns the current contents of the output stream as a byte array.
3 public String toString ()
Converts the contents of the buffer to a string. The translation will be performed according to the encoding set by default. Returns a string translated from the contents of the buffer.
4 public void write (int w)
Write the specified array to the output stream.
5 public void write (byte [] b, int, int len)
Write len the number of bytes starting offset from.
6 public void writeTo (OutputStream outSt)
Write the entire contents of the stream to the specified stream argument.

Example

Below is an example of demonstrating ByteArrayOutputStream and ByteArrayInputStream.

import java.io.*;
public class TestByteStream {

   public static void main(String args[])throws IOException {
      ByteArrayOutputStream outputByte = new ByteArrayOutputStream(12);

      while(outputByte.size()!= 12) {
        outputByte.write("hi wikitechy".getBytes()); 
      }
      byte a [] = outputByte.toByteArray();
      System.out.println("Output:");
      
      for(int i = 0 ; i < a.length; i++) {
         // Character Display
         System.out.print((char)a[i] + " "); 
      }
      System.out.println();
      
      int b;
      ByteArrayInputStream inputByte = new ByteArrayInputStream(a);
      System.out.println("Convert characters to uppercase:" );
      
      for(int j = 0 ; j < 1; j++) {
         while(( b = inputByte.read())!= -1) {
            System.out.println(Character.toUpperCase((char)b));
         }
         inputByte.reset(); 
      }
   }
}
click below button to copy the code. By - java tutorial - team

Output

Output:
h i   w i k i t e c h y 
Convert characters to uppercase:
H
I
 
W
I
K
I
T
E
C
H
Y

Related Searches to Java - Constructors and methods of the ByteArrayOutputStream class