Java ByteArrayOutputStream class

Introduction

ByteArrayOutputStream implements the output stream and uses a byte array as the destination.

ByteArrayOutputStream has two constructors, shown here:

ByteArrayOutputStream()  
ByteArrayOutputStream(int numBytes) 

The close() method has no effect on a ByteArrayOutputStream.

The following example demonstrates ByteArrayOutputStream:

// Demonstrate ByteArrayOutputStream. 

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

public class Main {
  public static void main(String args[]) {
    ByteArrayOutputStream f = new ByteArrayOutputStream();
    String s = "This should end up in the array";
    byte buf[] = s.getBytes();

    try {//from   w  w w .j a va 2 s.c  o  m
      f.write(buf);
    } catch (IOException e) {
      System.out.println("Error Writing to Buffer");
      return;
    }

    System.out.println("Buffer as a string");
    System.out.println(f.toString());
    System.out.println("Into array");
    byte b[] = f.toByteArray();
    for (int i = 0; i < b.length; i++)
      System.out.print((char) b[i]);

    System.out.println("\nTo an OutputStream()");

    // Use try-with-resources to manage the file stream.
    try (FileOutputStream f2 = new FileOutputStream("test.txt")) {
      f.writeTo(f2);
    } catch (IOException e) {
      System.out.println("I/O Error: " + e);
      return;
    }

    System.out.println("Doing a reset");
    f.reset();

    for (int i = 0; i < 3; i++) {
      f.write('X');
    }
    System.out.println(f.toString());
  }
}



PreviousNext

Related