问题
I want to take type UUID
and output it in a Base64
encoded format, however given the input methods on Base64
and outputs on UUID
how to accomplish this doesn't seem obvious.
update though not an explicit requirement for my use case, it would be nice to know if the method used uses the raw UUID (the 128 bits that a UUID actually is) of the UUID, as the standard hex encoding does.
回答1:
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);
回答2:
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));
}
}
来源:https://stackoverflow.com/questions/28129639/how-can-i-convert-a-uuid-to-base64