從以上程式可以發現,在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,很麻煩。