Java/Groovy中的Base64编码

Jos*_*h K 27 java grails groovy base64 encoding

在Java中将byte []转换为Base64字符串的正确方法是什么?更好的是Grails/Groovy,因为它告诉我该encodeAsBase64()函数已被弃用.sun.misc.BASE64Encoder建议不要使用该程序包,并在某些Windows平台上输出不同大小的字符串.

ata*_*lor 86

在groovy中执行此操作的首选方法是:

 def encoded = "Hello World".bytes.encodeBase64().toString()
 assert encoded == "SGVsbG8gV29ybGQ="
 def decoded = new String("SGVsbG8gV29ybGQ=".decodeBase64())
 assert decoded == "Hello World"
Run Code Online (Sandbox Code Playgroud)

  • 默认情况下,自版本1.6.0起,groovy不会在编码中插入额外的换行符.调用`encodeBase64(true)`可以启用该行为. (9认同)