Java InputStream read to byte array via ByteArrayOutputStream

Description

Java InputStream read to byte array via ByteArrayOutputStream

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

public class Main {

   public static void main(String args[]) throws IOException {
      String tmp = "abcde";
      byte b[] = tmp.getBytes();
      InputStream input1 = new ByteArrayInputStream(b);

      byte[] s = readBytes(input1);

      System.out.println(Arrays.toString(s));
   }// ww w. j  a  v a  2  s  .  c o m

   public static byte[] readBytes(InputStream stream) throws IOException {
      ByteArrayOutputStream b = new ByteArrayOutputStream();
      int readedBytes;
      byte[] buf = new byte[1024];
      while ((readedBytes = stream.read(buf)) > 0) {
         b.write(buf, 0, readedBytes);
      }
      b.close();
      return b.toByteArray();
   }

}



PreviousNext

Related