ByteArrayInputStream

In this chapter you will learn:

  1. How to use ByteArrayInputStream
  2. Mark and reset positions in ByteArrayInputStream

Use ByteArrayInputStream

ByteArrayInputStream is an implementation of an InputStream that uses a byte array as the source.

This class has two constructors, each of which requires a byte array to provide the data source:

  • ByteArrayInputStream(byte array[ ])
    array is the input source.
  • ByteArrayInputStream(byte array[ ], int start, int numBytes)
    uses a subset of your byte array.

The following code creates ByteArrayInputStream from byte array

import java.io.ByteArrayInputStream;
import java.io.IOException;
/*  ja v  a2s  .  c  o  m*/
public class Main {
  public static void main(String args[]) throws IOException {
    String tmp = "abcdefghijklmnopqrstuvwxyz";
    byte b[] = tmp.getBytes();
    ByteArrayInputStream input1 = new ByteArrayInputStream(b);
    ByteArrayInputStream input2 = new ByteArrayInputStream(b, 0, 3);
  }
}

Mark and reset positions in ByteArrayInputStream

A ByteArrayInputStream implements both mark( ) and reset( ). The following example uses the reset( ) method to read the same input twice.

import java.io.ByteArrayInputStream;
import java.io.IOException;
//j a va2s.co  m
public class Main {
  public static void main(String args[]) throws IOException {
    String tmp = "abc";
    byte b[] = tmp.getBytes();
    ByteArrayInputStream in = new ByteArrayInputStream(b);
    for (int i = 0; i < 2; i++) {
      int c;
      while ((c = in.read()) != -1) {
        if (i == 0) {
          System.out.print((char) c);
        } else {
          System.out.print(Character.toUpperCase((char) c));
        }
      }
      System.out.println();
      in.reset();

    }
  }
}

Next chapter...

What you will learn in the next chapter:

  1. How to use PrintStream
  2. Use PrintStream through System.out.printf
  3. Create PrintStream from File object and redirect System.out.println
  4. How to use PrintStream to print to a file