Java / Groovy 中的 Base64 编码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/4188406/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Base64 encoding in Java / Groovy
提问by Josh K
What is the proper way to convert a byte [] to a Base64 string in Java? Better yet would be Grails / Groovy because it tells me that the encodeAsBase64()function is deprecated. The sun.misc.BASE64Encoderpackage isn't recommended for use and outputs a different size string on some Windows platforms.
在 Java 中将字节 [] 转换为 Base64 字符串的正确方法是什么?更好的是 Grails/Groovy,因为它告诉我该encodeAsBase64()函数已被弃用。sun.misc.BASE64Encoder不推荐使用该包并在某些 Windows 平台上输出不同大小的字符串。
采纳答案by Evan Mulawski
Apache Commons has many utilities:
Apache Commons 有许多实用程序:
Binary Package: http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Base64.html
二进制包:http: //commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Base64.html
Download: http://commons.apache.org/codec/download_codec.cgi
回答by Mark O'Connor
You could use the open source Base64Coderlibrary
您可以使用开源Base64Coder库
import biz.source_code.base64Coder.Base64Coder
@Grab(group='biz.source_code', module='base64coder', version='2010-09-21')
String s1 = Base64Coder.encodeString("Hello world")
String s2 = Base64Coder.decodeString("SGVsbG8gd29ybGQ=")
回答by ataylor
The preferred way to do this in groovy is:
在 groovy 中执行此操作的首选方法是:
 def encoded = "Hello World".bytes.encodeBase64().toString()
 assert encoded == "SGVsbG8gV29ybGQ="
 def decoded = new String("SGVsbG8gV29ybGQ=".decodeBase64())
 assert decoded == "Hello World"
回答by srsajid
Implement your own method like this :)
像这样实现你自己的方法:)
public class Coder {
private static final String base64code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
public static String encodeAsBase64(String toEncode) {
    return encodeAsBase64(toEncode.getBytes())
}
public static String encodeAsBase64(byte[] toEncode) {
    int pos = 0;
    int onhand = 0;
    StringBuffer buffer = new StringBuffer();
    for(byte b in toEncode) {
        int read = b;
        int m;
        if(pos == 0) {
            m = (read >> 2) & 63;
            onhand = read & 3;
            pos = 1;
        } else if(pos == 1) {
            m = (onhand << 4) + ((read >> 4) & 15);
            onhand = read & 15;
            pos = 2;
        } else if(pos == 2) {
            m = ((read >> 6) & 3) + (onhand << 2);
            onhand = read & 63;
            buffer.append(base64code.charAt(m));
            m = onhand;
            onhand = 0;
            pos  = 0;
        }
        buffer.append(base64code.charAt(m));
    }
    while(pos > 0 && pos < 4) {
        pos++;
        if(onhand == -1) {
            buffer.append('=');
        } else {
            int m = pos == 2 ? onhand << 4 : (pos == 3 ? onhand << 2 : onhand);
            onhand = -1;
            buffer.append(base64code.charAt(m));
        }
    }
    return buffer.toString()
}
}
}
回答by Stefan Becker
(adding this to this thread in the hopes that somebody else will get a hit on this and doesn't have to waste his valuable time)
(将此添加到此线程中,希望其他人对此有所了解,而不必浪费他的宝贵时间)
I got stymied today when I tried to add in my Grails 2.3.11/Groovy 2.1.9 application the output of
今天,当我尝试在 Grails 2.3.11/Groovy 2.1.9 应用程序中添加
String src = render(
        model:    ...,
        template: ...,
    )
    .encodeAsBase64()
as a data-attribute to a DOM element. But the atob()in the corresponding JavaScript, i.e. the code that decodes the Base64 string from the data attribute, kept complaining about illegal characters, while other decoders, e.g. base64 -daccepted the same Base64 string without problems.
作为data-DOM 元素的属性。但是atob()在相应的 JavaScript 中,即从 data 属性解码 Base64 字符串的代码,不断抱怨非法字符,而其他解码器,例如,base64 -d接受相同的 Base64 字符串没有问题。
The solution is to force the render()return value to a single string and then apply the Base64 encoding, i.e.
解决办法是强制render()返回值为单个字符串,然后应用Base64编码,即
String src = render(
        model:    ...,
        template: ...,
    )
    .toString()
    .encodeAsBase64()
or (if you consider encodeAsBase64()as deprecated):
或(如果您认为encodeAsBase64()已弃用):
String src = render(
        model:    ...,
        template: ...,
    )
    .toString()
    .bytes
    .encodeBase64() // add 'true' for chunked output

