Convert InputStream to byte array in Java

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

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

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

    You can use cactoos library with provides reusable object-oriented Java components. OOP is emphasized by this library, so no static methods, NULLs, and so on, only real objects and their contracts (interfaces). A simple operation like reading InputStream, can be performed like that

    final InputStream input = ...;
    final Bytes bytes = new BytesOf(input);
    final byte[] array = bytes.asBytes();
    Assert.assertArrayEquals(
        array,
        new byte[]{65, 66, 67}
    );
    

    Having a dedicated type Bytes for working with data structure byte[] enables us to use OOP tactics for solving tasks at hand. Something that a procedural "utility" method will forbid us to do. For example, you need to enconde bytes you've read from this InputStream to Base64. In this case you will use Decorator pattern and wrap Bytes object within implementation for Base64. cactoos already provides such implementation:

    final Bytes encoded = new BytesBase64(
        new BytesOf(
            new InputStreamOf("XYZ")
        )
    );
    Assert.assertEquals(new TextOf(encoded).asString(), "WFla");
    

    You can decode them in the same manner, by using Decorator pattern

    final Bytes decoded = new Base64Bytes(
        new BytesBase64(
            new BytesOf(
                new InputStreamOf("XYZ")
            )
        )
    );
    Assert.assertEquals(new TextOf(decoded).asString(), "XYZ");
    

    Whatever your task is you will be able to create own implementation of Bytes to solve it.

提交回复
热议问题