Java InputStream read to String via ByteArrayOutputStream

Description

Java InputStream read to String via ByteArrayOutputStream

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

public class Main {

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

      String s = readString(input1);

      System.out.println(s);/*from   www .j av  a  2  s.c  o  m*/
   }

   public static String readString(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.toString();
   }

}



PreviousNext

Related