Convert the content of a byte buffer to a Base64 encoded string - Java java.nio

Java examples for java.nio:ByteBuffer Convert

Description

Convert the content of a byte buffer to a Base64 encoded string

Demo Code


import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class Main{
    /**/*from   w ww  .j  a  va  2  s  .c  om*/
     * 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.encode(b);

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

Related Tutorials