我一直在尝试进行对象序列化和Base64编码结果。它适用于Sun的lib:
Bean01 bean01 = new Bean01();
bean01.setDefaultValues();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
new ObjectOutputStream( baos ).writeObject( bean01 );
System.out.println(Base64.encode(baos.toByteArray()));
这很好。但是,我想使用org.apache.commons.codec.binary.base64进行相同的操作,但这不会返回相同的字符串:
System.out.println(org.apache.commons.codec.binary.Base64.encodeBase64(baos.toByteArray()));
使用Apache的编码器来实现byteArray的正确Base64编码的正确方法是什么?
实际上,commons-codec
您使用的版本和特定的Sun内部版本的确提供相同的结果。我认为您认为他们提供了不同的版本,因为toString()
这样做时您隐式地调用了数组:
System.out.println(org.apache.commons.codec.binary.Base64.encodeBase64(baos.toByteArray()));
这绝对不会打印出数组内容。而是只会打印出数组引用的地址。
我编写了以下程序来测试编码器彼此之间的相对关系。您将从下面的输出中看到给出相同的结果:
import java.util.Random;
public class Base64Stuff
{
public static void main(String[] args) {
Random random = new Random();
byte[] randomBytes = new byte[32];
random.nextBytes(randomBytes);
String internalVersion = com.sun.org.apache.xerces.internal.impl.dv.util.Base64.encode(randomBytes);
byte[] apacheBytes = org.apache.commons.codec.binary.Base64.encodeBase64(randomBytes);
String fromApacheBytes = new String(apacheBytes);
System.out.println("Internal length = " + internalVersion.length());
System.out.println("Apache bytes len= " + fromApacheBytes.length());
System.out.println("Internal version = |" + internalVersion + "|");
System.out.println("Apache bytes = |" + fromApacheBytes + "|");
System.out.println("internal equal apache bytes?: " + internalVersion.equals(fromApacheBytes));
}
}
这是它的运行结果:
Internal length = 44
Apache bytes len= 44
Internal version = |Kf0JBpbxCfXutxjveYs8CXMsFpQYgkllcHHzJJsz9+g=|
Apache bytes = |Kf0JBpbxCfXutxjveYs8CXMsFpQYgkllcHHzJJsz9+g=|
internal equal apache bytes?: true
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句