ByteArrayOutputStream class

                                          
    java.lang.Object                                     
     |                                    
     |--java.io.OutputStream                                 
         |                                
         |--java.io.ByteArrayOutputStream                             
                                          

This class implements an output stream in which the data is written into a byte array.

ConstructorSummary
ByteArrayOutputStream()Creates a new byte array output stream.
ByteArrayOutputStream(int size)Creates a new byte array output stream, with a buffer capacity of the specified size, in bytes.

ReturnMethodSummary
voidclose()Closing a ByteArrayOutputStream has no effect.
voidreset()Resets the count field of this byte array output stream to zero, so that all currently accumulated output in the output stream is discarded.
intsize()Returns the current size of the buffer.
byte[]toByteArray()Creates a newly allocated byte array.
StringtoString()Converts the buffer's contents into a string decoding bytes using the platform's default character set.
StringtoString(String charsetName)Converts the buffer's contents into a string by decoding the bytes using the specified charsetName.
voidwrite(byte[] b, int off, int len)Writes len bytes from the specified byte array starting at offset off to this byte array output stream.
voidwrite(int b)Writes the specified byte to this byte array output stream.
voidwriteTo(OutputStream out)Writes the complete contents of this byte array output stream to the specified output stream argument, as if by calling the output stream's write method using out.write(buf, 0, count).
Revised from Open JDK source code

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class Main {
  public static void main(String args[]) throws IOException {
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    outStream.write('a');
    outStream.write(("java2s.com").getBytes());
    System.out.println("outstream: " + outStream);
    System.out.println("size: " + outStream.size());
    outStream.close();
  }
}

The output:


outstream: ajava2s.com
size: 11

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;

public class Main {
  public static void main(String args[]) throws IOException {
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    outStream.write('a');
    outStream.write(("java2s.com").getBytes());
   
    System.out.println(Arrays.toString(outStream.toByteArray()));
    System.out.println(new String(outStream.toByteArray()));
    outStream.close();
  }
}

The output:


[97, 106, 97, 118, 97, 50, 115, 46, 99, 111, 109]
ajava2s.com
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.