Reading a binary input stream into a single byte array in Java

前端 未结 6 1894
陌清茗
陌清茗 2020-11-27 18:10

The documentation says that one should not use available() method to determine the size of an InputStream. How can I read the whole content of an <

6条回答
  •  孤城傲影
    2020-11-27 19:04

    The simplest approach IMO is to use Guava and its ByteStreams class:

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

    Or for a file:

    byte[] bytes = Files.toByteArray(file);
    

    Alternatively (if you didn't want to use Guava), you could create a ByteArrayOutputStream, and repeatedly read into a byte array and write into the ByteArrayOutputStream (letting that handle resizing), then call ByteArrayOutputStream.toByteArray().

    Note that this approach works whether you can tell the length of your input or not - assuming you have enough memory, of course.

提交回复
热议问题