Issue
I am trying to convert a ByteArray to Base64 in a Spring project, written in Kotlin. I have checked existing posts but they didnt help me. Actually I am trying to convert a blob to base, but I converted the blob to byteArray so far and am struggling now to convert the bytearray to base64. This is what I am currently trying:
var inByteArray = Base64.encodeBase64(blobAsBytes) //inByteArray : ByteArray!
var inByteArrayFormatted = Base64Utils.decode(inByteArray) //inByteArrayFormatted : ByteArray
I tried the things from this post How do I convert a byte array to Base64 in Java?, but they are just encoding strings but not directly to Base64. How can I convert a byte array to Base64? Not encoded strings but Base64?
Thanks for every help!
Solution
If you are using Kotlin with Java, you can use java.util.Base64
to encode a ByteArray
into a String
. I wrote an extension function to do this:
fun ByteArray.toBase64(): String =
String(Base64.getEncoder().encode(this))
// Use:
val b64 = "asdf".toByteArray().toBase64()
// YXNkZg==
Answered By - Todd
Answer Checked By - David Goodson (JavaFixing Volunteer)