在Java中將byte []轉換爲Base64字符串的正確方法是什麼?更好的是Grails/Groovy,因爲它告訴我encodeAsBase64()
函數已被棄用。不推薦使用sun.misc.BASE64Encoder
軟件包,並在某些Windows平臺上輸出不同的字符串。Java中的Base64編碼/ Groovy
22
A
回答
12
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
實現自己的方法,這樣:)
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()
}
}
相關問題
- 1. 編碼的BufferedImage爲Base64在JRuby中(JAVA)
- 2. Base64在Java中的Ascii編碼
- 3. java字符串base64編碼
- 4. base64編碼問題,java
- 5. 的Java使用Base64編碼和解碼
- 6. Base64編碼爲base64,
- 7. C# - Base64編碼JPEG到Base64編碼BMP
- 8. Base64解碼/使用java/android編碼
- 9. 編碼base64在C#解碼在Java
- 10. 的Java Base64編碼給出比C的base64編碼不同的結果
- 11. Java Base64編碼的字符串與.NET Base64編碼的字符串
- 12. 使用java的base64圖像編碼
- 13. 在Powershell中的Base64編碼
- 14. Sproutcore中的Base64編碼
- 15. Python中的base64編碼
- 16. Base64在Oracle中編譯java源代碼時出錯sql
- 17. Base64編碼解碼
- 18. Lua的Base64編碼
- 19. JavaMail的base64編碼
- 20. Android的Base64編碼
- 21. NSString的Base64編碼
- 22. 的Javascript Base64編碼
- 23. C#:Base64編碼
- 24. Cookie編碼Base64
- 25. Base64編碼
- 26. Backbone base64編碼
- 27. Java中BASE64類的編碼/解碼算法的效率如何?
- 28. 在Java中編碼base64並在C#中解碼
- 29. 在Java中編碼base64和在C#中解碼
- 30. Base64在Coffeescript中的編碼/解碼
這樣做的問題是,'encodeBase64'放線行結束在每隔76個字符其中弄亂的長度串。我最終使用'def encoded = byteArray.collect {it as char}'而不是Base64編碼。 – 2010-11-16 12:48:16
默認情況下,從版本1.6.0開始,groovy不會在編碼中插入額外的換行符。調用'encodeBase64(true)'啓用該行爲。 – ataylor 2010-11-16 17:10:08
+1對於一個簡單,簡潔的解決方案,我可以使用一個快速的小腳本(沒有任何lib deps)我需要檢查一些事情:-) – jpswain 2011-06-26 20:03:13