Convert InputStream to byte array in Java

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

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

30条回答
  •  情话喂你
    2020-11-21 12:51

    Use vanilla Java's DataInputStream and its readFully Method (exists since at least Java 1.4):

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

    There are some other flavors of this method, but I use this all the time for this use case.

提交回复
热议问题