Convert InputStream to byte array in Java

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

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

30条回答
  •  遇见更好的自我
    2020-11-21 12:38

    Java 8 way (thanks to BufferedReader and Adam Bien)

    private static byte[] readFully(InputStream input) throws IOException {
        try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input))) {
            return buffer.lines().collect(Collectors.joining("\n")).getBytes();
        }
    }
    

    Note that this solution wipes carriage return ('\r') and can be inappropriate.

提交回复
热议问题