Convert InputStream to byte array in Java

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

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

30条回答
  •  既然无缘
    2020-11-21 12:33

    I tried to edit @numan's answer with a fix for writing garbage data but edit was rejected. While this short piece of code is nothing brilliant I can't see any other better answer. Here's what makes most sense to me:

    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();
    

    btw ByteArrayOutputStream need not be closed. try/finally constructs omitted for readability

提交回复
热议问题