Java Base64 decode to byte array

Description

Java Base64 decode to byte array


import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Base64;

public class Main {
  public static void main(String[] argv) throws Exception {
    byte[] array = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };

    String s = toBase64String(array);
    //from   w  ww . j  av a2 s.c  om
    array = Base64.getDecoder().decode(s);
    
    System.out.println(Arrays.toString(array));
  }

  /**
   * Convert the content of a byte buffer to a Base64 encoded string
   */
  public static String toBase64String(ByteBuffer buff) {

    ByteBuffer bb = buff.asReadOnlyBuffer();
    bb.position(0);
    byte[] b = new byte[bb.limit()];
    bb.get(b, 0, b.length);
    return Base64.getEncoder().encodeToString(b);

  }

  public static String toBase64String(byte[] buff) {
    return (toBase64String(ByteBuffer.wrap(buff)));
  }

  public static String toBase64String(String string) {
    return (toBase64String(string.getBytes()));
  }
}



PreviousNext

Related