Java ByteBuffer convert to Base64 String

Description

Java ByteBuffer convert to Base64 String

import java.nio.ByteBuffer;
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 };
    ByteBuffer bb = ByteBuffer.wrap(array);
    System.out.println(toBase64String(bb));
  }//  www . j a v a2  s  .  c  o  m

  /**
   * 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