Java ByteArrayInputStream convert to String

Description

Java ByteArrayInputStream convert to String

import java.io.ByteArrayInputStream;

public class Main {

   public static void main(String args[]) {
      String tmp = "abcdefghijklmnopqrstuvwxyz";
      byte b[] = tmp.getBytes();
      ByteArrayInputStream input1 = new ByteArrayInputStream(b);
      ByteArrayInputStream input2 = new ByteArrayInputStream(b, 0, 3);

      String s = toString(input1);

      String s2 = toString(input2);

      System.out.println(s);//from   w ww . j  av a 2s .  c  o  m
      System.out.println(s2);
   }

   public static String toString(ByteArrayInputStream is) {
      int size = is.available();
      char[] theChars = new char[size];
      byte[] bytes = new byte[size];

      is.read(bytes, 0, size);
      for (int i = 0; i < size;)
         theChars[i] = (char) (bytes[i++] & 0xff);

      return new String(theChars);
   }
}



PreviousNext

Related