convert InputStream to ByteArray in java



Following method can be used to convert an InputStream to a Byte[].

Example

public static byte[] getBytes(InputStream is) throws IOException
{
   try (ByteArrayOutputStream os = new ByteArrayOutputStream();) {
      byte[] buffer = new byte[1024];
      for (int len = 0; (len = is.read(buffer)) != -1;) {
         os.write(buffer, 0, len);
      }
      os.flush();
      return os.toByteArray();
   }
}

Advertisements