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


当前回答

你可以使用Cactoos(我是它的开发者之一):

import org.cactoos.bytes.BytesOf;
byte[] array = new BytesOf(stream).asBytes();

你也可以将流转换为字符串:

import org.cactoos.text.TextOf;
String txt = new TextOf(stream).asString();

asBytes()和asString()方法都会抛出checked Exception。如果你不想捕获它,使用Unchecked*装饰器,例如:

import org.cactoos.bytes.BytesOf;
import org.cactoos.bytes.UncheckedBytes;
byte[] array = new UncheckedBytes(new BytesOf(stream)).asBytes();

其他回答

您需要从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();

下面的代码

public static byte[] serializeObj(Object obj) throws IOException {
  ByteArrayOutputStream baOStream = new ByteArrayOutputStream();
  ObjectOutputStream objOStream = new ObjectOutputStream(baOStream);

  objOStream.writeObject(obj); 
  objOStream.flush();
  objOStream.close();
  return baOStream.toByteArray(); 
} 

OR

BufferedImage img = ...
ByteArrayOutputStream baos = new ByteArrayOutputStream(1000);
ImageIO.write(img, "jpeg", baos);
baos.flush();
byte[] result = baos.toByteArray();
baos.close();

Java 7及以上版本:

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

如果由于某种原因,它不在表中,则将其包装在DataInputStream中,只需使用read来锤击它,直到它给您一个-1或您所要求的整个块。

public int readFully(InputStream in, byte[] data) throws IOException {
    int offset = 0;
    int bytesRead;
    boolean read = false;
    while ((bytesRead = in.read(data, offset, data.length - offset)) != -1) {
        read = true;
        offset += bytesRead;
        if (offset >= data.length) {
            break;
        }
    }
    return (read) ? offset : -1;
}

你可以试试仙人掌:

byte[] array = new BytesOf(stream).bytes();