从以上程式可以发现,在Java用Base64一点都不难,不用几行程式码就解决了!只是这个sun.mis c套件所提供的Base64功能,编码和解码的效率并不太好,而且在以后的Java版本可能就不被支援了,完全不建议使用。
Apache Commons Codec作法
Apache Commons Codec有提供Base64的编码与解码功能,会使用到org.apache.commons.codec.binary套件下的Base64类别,用法如下:
final Base64 base64 = new Base64(); final String text = "字串文字"; final byte[] textByte = text.getBytes("UTF-8"); //编码 final String encodedText = base64.encodeToString(textByte); System.out.println(encodedText); //解码 System.out.println(new String(base64.decode(encodedText), "UTF-8")); final Base64 base64 = new Base64(); final String text = "字串文字"; final byte[] textByte = text.getBytes("UTF-8"); //编码 final String encodedText = base64.encodeToString(textByte); System.out.println(encodedText); //解码 System.out.println(new String(base64.decode(encodedText), "UTF-8"));
以上的程式码看起来又比早期用sun.mis c套件还要更精简,效能实际执行起来也快了不少。缺点是需要引用Apache Commons Codec,很麻烦。