Convert InputStream to byte array in Java

前端 未结 30 3536
無奈伤痛
無奈伤痛 2020-11-21 12:08

How do I read an entire InputStream into a byte array?

30条回答
  •  感情败类
    2020-11-21 12:41

    Safe solution (with capability of close streams correctly):

    • Java 9+:

       final byte[] bytes;
       try (inputStream) {
           bytes = inputStream.readAllBytes();
       }
      

    • Java 8:

       public static byte[] readAllBytes(InputStream inputStream) throws IOException {
           final int bufLen = 4 * 0x400; // 4KB
           byte[] buf = new byte[bufLen];
           int readLen;
           IOException exception = null;
      
           try {
               try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                   while ((readLen = inputStream.read(buf, 0, bufLen)) != -1)
                       outputStream.write(buf, 0, readLen);
      
                   return outputStream.toByteArray();
               }
           } catch (IOException e) {
               exception = e;
               throw e;
           } finally {
               if (exception == null) inputStream.close();
               else try {
                   inputStream.close();
               } catch (IOException e) {
                   exception.addSuppressed(e);
               }
           }
       }
      

    • Kotlin (when Java 9+ isn't accessible):

       @Throws(IOException::class)
       fun InputStream.readAllBytes(): ByteArray {
           val bufLen = 4 * 0x400 // 4KB
           val buf = ByteArray(bufLen)
           var readLen: Int = 0
      
           ByteArrayOutputStream().use { o ->
               this.use { i ->
                   while (i.read(buf, 0, bufLen).also { readLen = it } != -1)
                       o.write(buf, 0, readLen)
               }
      
               return o.toByteArray()
           }
       }
      

      To avoid nested use see here.


    • Scala (when Java 9+ isn't accessible) (By @Joan. Thx):

      def readAllBytes(inputStream: InputStream): Array[Byte] =
        Stream.continually(inputStream.read).takeWhile(_ != -1).map(_.toByte).toArray
      

提交回复
热议问题