How to Base64 encode a Java object using org.apache.commons.codec.binary.base64?

后端 未结 2 1724
傲寒
傲寒 2021-02-13 02:52

I\'ve been trying to do an object serialization and Base64 encode the result. It works with Sun\'s lib:

Bean01 bean01 = new Bean01();
bean01.setDefaultValues();
         


        
2条回答
  •  自闭症患者
    2021-02-13 03:16

    Actually the commons-codec version and specific Sun internal version you are using do give the same results. I think you thought they were giving different versions because you are implicitly calling toString() on an array when you do:

    System.out.println(org.apache.commons.codec.binary.Base64.encodeBase64(baos.toByteArray()));
    

    which is definitely does not print out the array contents. Instead, that will only print out the address of the array reference.

    I've written the following program to test the encoders against each other. You'll see from the output below that the give the same results:

    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));
        }
    }
    

    And here's the output from a run of it:

    Internal length = 44
    Apache bytes len= 44
    Internal version = |Kf0JBpbxCfXutxjveYs8CXMsFpQYgkllcHHzJJsz9+g=|
    Apache bytes     = |Kf0JBpbxCfXutxjveYs8CXMsFpQYgkllcHHzJJsz9+g=|
    internal equal apache bytes?: true
    

提交回复
热议问题