实际上,您正在使用的版本和特定的 Sun 内部版本确实给出了相同的结果。我想你认为他们给出了不同的版本,因为当你这样做时,你正在隐式调用一个数组:commons-codec
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