【Java基础】sun.misc.BASE64和Java 8 java.util.Base64区别

今天项目中遇到了一个问题,同样的使用Base64 encode的时候,发现有二个Base64类可以encode,使用misc的 BASE64Encoder 方法 encode,生成的String和util包的Base64生成String有什么区别呢?

 写了个程序,把一段内容使用不同的方法encode,如下图所示:misc的Base64会自动加\n, 为什么要这样呢?

简单事例代码:

byte[] bytes = new byte[57];
String enc1 = new sun.misc.BASE64Encoder().encode(bytes);
String enc2 = new String(java.util.Base64.getMimeEncoder().encode(bytes),
                         StandardCharsets.UTF_8);

System.out.println("enc1 = <" + enc1 + ">");
System.out.println("enc2 = <" + enc2 + ">");
System.out.println(enc1.equals(enc2));

输出:

byte[] bytes = new byte[57];
String enc1 = new sun.misc.BASE64Encoder().encode(bytes);
String enc2 = new String(java.util.Base64.getMimeEncoder().encode(bytes),
                         StandardCharsets.UTF_8);

System.out.println("enc1 = <" + enc1 + ">");
System.out.println("enc2 = <" + enc2 + ">");
System.out.println(enc1.equals(enc2));
sun.misc.BASE64Encoder encode时每76个字符就会生成一个'\n',java.util.Base64不会有换行符的产生。
java.util.Base64的作者认为 sun.misc.BASE64Encoder 这个做法是个bug,我也认为是的,因为在我使用sun.misc.BASE64Encoder encode之后的String,在HTTP请求Head中放时 \n HTTP请求检查头部参数会报错,不认换行符。

参考:https://stackoverflow.com/questions/35301409/migrating-from-sun-misc-base64-to-java-8-java-util-base64

猜你喜欢

转载自www.cnblogs.com/zhengwangzw/p/10908417.html