如何将整个输入流读到字节数组?


当前回答

/*InputStream class_InputStream = null;
I am reading class from DB 
class_InputStream = rs.getBinaryStream(1);
Your Input stream could be from any source
*/
int thisLine;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((thisLine = class_InputStream.read()) != -1) {
    bos.write(thisLine);
}
bos.flush();
byte [] yourBytes = bos.toByteArray();

/*Don't forget in the finally block to close ByteArrayOutputStream & InputStream
 In my case the IS is from resultset so just closing the rs will do it*/

if (bos != null){
    bos.close();
}

其他回答

您需要从InputStream中读取每个字节,并将其写入ByteArrayOutputStream。

然后你可以通过调用toByteArray()来检索底层的字节数组:

InputStream is = ...
ByteArrayOutputStream buffer = new ByteArrayOutputStream();

int nRead;
byte[] data = new byte[16384];

while ((nRead = is.read(data, 0, data.length)) != -1) {
  buffer.write(data, 0, nRead);
}

return buffer.toByteArray();
/*InputStream class_InputStream = null;
I am reading class from DB 
class_InputStream = rs.getBinaryStream(1);
Your Input stream could be from any source
*/
int thisLine;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((thisLine = class_InputStream.read()) != -1) {
    bos.write(thisLine);
}
bos.flush();
byte [] yourBytes = bos.toByteArray();

/*Don't forget in the finally block to close ByteArrayOutputStream & InputStream
 In my case the IS is from resultset so just closing the rs will do it*/

if (bos != null){
    bos.close();
}

20年后,终于有了一个不需要第三方库的简单解决方案,这要感谢Java 9:

InputStream is;
…
byte[] array = is.readAllBytes();

还要注意方便的方法readNBytes(byte[] b, int off, int len)和transferTo(OutputStream)来解决重复的需求。

如果你碰巧使用谷歌Guava,它将像使用ByteStreams一样简单:

byte[] bytes = ByteStreams.toByteArray(inputStream);

安全解决方案(正确关闭流):

Java 9及更新版本: 最终字节[]字节; try (inputStream) { 字节= inputStream.readAllBytes(); }


Java 8 and older: 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(当Java 9+不可访问时): @Throws (IOException::类) fun InputStream.readAllBytes(): ByteArray { val bufLen = 4 * 0x400 // 4KB val buf = ByteArray(bufLen) var readLen: Int = 0 ByteArrayOutputStream()。使用{o -> 这一点。使用{I -> i.read(buf, 0, bufLen)。{readLen = it} != -1) o.write(buf, 0, readLen) } 返回o.toByteArray () } } 避免嵌套使用请看这里。


Scala(当Java 9+不可访问时)(By @Joan。Thx): def readAllBytes(inputStream: inputStream): Array[Byte] = Stream.continually (read)。takeWhile(_ != -1).map(_. tobyte).toArray . take (_