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


当前回答

请参阅InputStream.available()文档:

It is particularly important to realize that you must not use this method to size a container and assume that you can read the entirety of the stream without needing to resize the container. Such callers should probably write everything they read to a ByteArrayOutputStream and convert that to a byte array. Alternatively, if you're reading from a file, File.length returns the current length of the file (though assuming the file's length can't change may be incorrect, reading a file is inherently racy).

其他回答

ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
while (true) {
    int r = in.read(buffer);
    if (r == -1) break;
    out.write(buffer, 0, r);
}

byte[] ret = out.toByteArray();

我试图编辑@numan的答案,修复了写垃圾数据,但编辑被拒绝。虽然这段简短的代码并不出色,但我看不到其他更好的答案。以下是我认为最有意义的建议:

ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024]; // you can configure the buffer size
int length;

while ((length = in.read(buffer)) != -1) out.write(buffer, 0, length); //copy streams
in.close(); // call this in a finally block

byte[] result = out.toByteArray();

ByteArrayOutputStream不需要关闭。为了可读性,省略了一些结构

Java 7及以上版本:

import sun.misc.IOUtils;
...
InputStream in = ...;
byte[] buf = IOUtils.readFully(in, -1, false);

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

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

使用普通Java的DataInputStream和它的readFully方法(至少从Java 1.4开始存在):

...
byte[] bytes = new byte[(int) file.length()];
DataInputStream dis = new DataInputStream(new FileInputStream(file));
dis.readFully(bytes);
...

这个方法还有其他一些形式,但在这个用例中,我一直使用这个方法。