Convert InputStream to byte array in Java

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

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

30条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-21 12:37

    You're doing an extra copy if you use ByteArrayOutputStream. If you know the length of the stream before you start reading it (e.g. the InputStream is actually a FileInputStream, and you can call file.length() on the file, or the InputStream is a zipfile entry InputStream, and you can call zipEntry.length()), then it's far better to write directly into the byte[] array -- it uses half the memory, and saves time.

    // Read the file contents into a byte[] array
    byte[] buf = new byte[inputStreamLength];
    int bytesRead = Math.max(0, inputStream.read(buf));
    
    // If needed: for safety, truncate the array if the file may somehow get
    // truncated during the read operation
    byte[] contents = bytesRead == inputStreamLength ? buf
                      : Arrays.copyOf(buf, bytesRead);
    

    N.B. the last line above deals with files getting truncated while the stream is being read, if you need to handle that possibility, but if the file gets longer while the stream is being read, the contents in the byte[] array will not be lengthened to include the new file content, the array will simply be truncated to the old length inputStreamLength.

提交回复
热议问题