简体   繁体   中英

Convert InputStream to base64 and then to byte array

I need a byte array, but the requirement is like first I need to convert the input stream to base64 and then the base64 to byte array.

I have tried directly to the byte array, but the requirement is like need to convert the InputStream to base64 and then byte[].

InputStream input = ....
byte[] byteArray = IOUtils.toByteArray(input);

You can use Base64 from java.util package to encode your stream to base 64

Something like this:

    String initialString = "original text";
    InputStream input = new ByteArrayInputStream(initialString.getBytes());

    byte[] byteEncoded = Base64.getEncoder().encode(IOUtils.toByteArray(input));

The method is Base64.getEncoder().encode and have 3 candidates:

  • public byte[] encode(byte[] src

  • public int encode(byte[] src,byte[] dst)

  • public ByteBuffer encode(ByteBuffer buffer)

Hoping that help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM