在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