2010-11-15 394 views
22

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

回答

2

你可以使用开源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=") 
76

做的首选方式这在groovy是:

def encoded = "Hello World".bytes.encodeBase64().toString() 
assert encoded == "SGVsbG8gV29ybGQ=" 
def decoded = new String("SGVsbG8gV29ybGQ=".decodeBase64()) 
assert decoded == "Hello World" 
+0

这样做的问题是,'encodeBase64'放线行结束在每隔76个字符其中弄乱的长度串。我最终使用'def encoded = byteArray.collect {it as char}'而不是Base64编码。 – 2010-11-16 12:48:16

+9

默认情况下,从版本1.6.0开始,groovy不会在编码中插入额外的换行符。调用'encodeBase64(true)'启用该行为。 – ataylor 2010-11-16 17:10:08

+2

+1对于一个简单,简洁的解决方案,我可以使用一个快速的小脚本(没有任何lib deps)我需要检查一些事情:-) – jpswain 2011-06-26 20:03:13

0

实现自己的方法,这样:)

public class Coder { 
private static final String base64code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/"; 

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() 
} 

}