How can I convert a UUID to base64?

蓝咒 提交于 2019-12-05 14:19:38

First, convert your UUID to a byte buffer for consumption by a Base64 encoder:

ByteBuffer uuidBytes = ByteBuffer.wrap(new bytes[16]);
uuidBytes.putLong(uuid.getMostSignificantBits());
uuidBytes.putLong(uuid.getLeastSignificantBits());

Then encode that using the encoder:

byte[] encoded = encoder.encode(uuidBytes);

Alternatively, you can get a Base64-encoded string like this:

String encoded = encoder.encodeToString(uuidBytes);

You can use Base64 from apache commons codecs. https://commons.apache.org/proper/commons-codec/apidocs/org/apache/commons/codec/binary/Base64.html

import java.util.UUID;
import org.apache.commons.codec.binary.Base64;

public class Test {

    public static void main(String[] args) {
        String uid = UUID.randomUUID().toString();
        System.out.println(uid);
        byte[] b = Base64.encodeBase64(uid.getBytes());
        System.out.println(new String(b));
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!