sun.misc.BASE64Encoder / Decoder用于获取byte
我试图使用sun.misc.BASE64Encoder / Decoder,但是这段代码:
(new sun.misc BASE64Encoder()).encode(new sun.misc.BASE64Decoder().decodeBuffer("test string XML:"))
返回“test / string / XML /”我很尴尬
不要使用sun.misc
或com.sun
类。 它们不能保证在不同版本的jre之间保持一致。
使用commons-codec Base64.encodeBase64(..)
和Base64.decodeBase64(..)
使用类:
javax.xml.bind.DatatypeConverter
它有两种感兴趣的方法:
public static byte[] parseBase64Binary( String lexicalXSDBase64Binary ) public static String printBase64Binary( byte[] val )
您首先解码字符串“test string XML:”,它不是真正有效的Base64,因为它包含空格和冒号,其中没有一个是有效的B64字符。 我认为你打算编码然后解码 ,像这样:
(new sun.misc.BASE64Decoder().decodeBuffer(new sun.misc.BASE64Encoder().encode("test string XML:"))
我想你想要:
String s = "Hello world"; new sun.misc.BASE64Encoder().encode(s.getBytes("UTF-8"));
更好的是,使用commons utils作为之前的答案建议。 如果你不能在另一个jar上添加外部依赖,那么只能使用sun.misc.Base64Encoder。