在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. Base64在Java中的Ascii编码
- 2. java字符串base64编码
- 3. 的Java使用Base64编码和解码
- 4. Base64编码为base64,
- 5. Base64解码/使用java/android编码
- 6. 的Java Base64编码给出比C的base64编码不同的结果
- 7. Java Base64编码的字符串与.NET Base64编码的字符串
- 8. Python中的base64编码
- 9. 的Javascript Base64编码
- 10. JavaMail的base64编码
- 11. Base64编码
- 12. Cookie编码Base64
- 13. Java中BASE64类的编码/解码算法的效率如何?
- 14. 在Java中编码base64和在C#中解码
- 15. 在Java中编码base64并在C#中解码
- 16. Base64在Coffeescript中的编码/解码
- 17. Base64在C#中编码PDF?
- 18. Base64编码图像
- 19. Base64编码问题
- 20. 检测base64编码
- 21. iPhone 3.2 Base64编码
- 22. Base64编码新行
- 23. Base64编码图像
- 24. 编码/解码.EXE为Base64编码
- 25. JavaScript中的JSON编码/解码base64编码/解码
- 26. Android:编码和解码base64
- 27. Base64编码和解码
- 28. Base64编码解码卡住
- 29. 使用Base64编码的JsonResult
- 30. 上传的UIImage base64编码
这样做的问题是,'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