convert InputStream to ByteArray in java

Java 8Object Oriented ProgrammingProgramming

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();
   }
}
raja
Published on 06-Feb-2018 08:35:42
Advertisements