2010-11-15 75 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() 
} 

}