Search code examples
javajava-8inputstream

Java 1.8 and below equivalent for InputStream.readAllBytes()


I wrote a program that gets all bytes from an InputStream in Java 9 with

InputStream.readAllBytes()

Now, I want to export it to Java 1.8 and below. Is there an equivalent function? Couldn't find one.


Solution

  • Here's one way to solve this without relying on third-party libraries:

    inputStream.reset();
    byte[] bytes = new byte[inputStream.available()];
    DataInputStream dataInputStream = new DataInputStream(inputStream);
    dataInputStream.readFully(bytes);
    

    Or if you don't mind using thirdparties (Commons IO):

    
    byte[] bytes = IOUtils.toByteArray(is);
    

    Guava also helps:

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