Java Base64编码解码实现

时间:2023-03-09 07:53:05
Java Base64编码解码实现

我尝试过两种方式:java自带的sun.misc的工具类,还有commons-codec.jar

1、sun.misc的工具类

         String encoderStr = null;
BASE64Encoder encoder = new BASE64Encoder();
try {
encoderStr = encoder.encode(str.getBytes(DEFAULT_CHARSET));
} catch (UnsupportedEncodingException e) {
log.error("字符串【" + str + "】base64编码失败", e);
}

但测试的结果发现,需要自行对\r和\n做replaceAll替换为“”,得到的str才是正确的。

2、commons-codec.jar

  这个第三方开源jar包也提供了对文件的编码和解码,简单也很好用,建议

String strBase64 = base64.encodeToString(tempStrBase64.toString().getBytes(DEFAULT_CHARSET));

  其他用法,请参考api:

    http://commons.apache.org/proper/commons-codec/apidocs/org/apache/commons/codec/binary/Base64.html

  对比较小的文件编码、解码:

 byte[] source = ...; // load your data here

 byte[] encoded = Base64.encode(source);

 byte[] decoded = Base64.decode(encoded);

  对比较大的文件编码、解码:

 InputStream inputStream = new FileInputStream("source.jpg");

 OutputStream outputStream = new FileOutputStream("encoded.b64");

 Base64.encode(inputStream, outputStream);

 outputStream.close();

 inputStream.close();

 代码示例Base64解码:

 InputStream inputStream = new FileInputStream("encoded.b64");

 OutputStream outputStream = new FileOutputStream("decoded.jpg");

 Base64.decode(inputStream, outputStream);

 outputStream.close();

 inputStream.close();