看了太多计算的方式,也验证了下,这里个人总结一下,此处主要针对 java.util.Base64 来总结一下:
方式一:
Base64.getMimeEncoder().encode(readBuf)
Base64类中源码方法如下:
/**
* Returns a {@link Encoder} that encodes using the
* <a href="#mime">MIME</a> type base64 encoding scheme.
*
* @return A Base64 encoder.
*/
public static Encoder getMimeEncoder() {
return Encoder.RFC2045;
}
使用此种方式encode则采用如下方式计算长度:
private static final int MIMELINEMAX = 76;
private static final byte[] CRLF = new byte[]{'\r', '\n'};
/**
* 根据原数据长度获取Base64长度
*
* @param length
* @return
*/
public static Long getBase64Len(Long length) {
long len = 4 * ((length + 2) / 3);
if (MIMELINEMAX > 0)
len += (len - 1) / MIMELINEMAX * CRLF.length;
return len;
}
方式二:
Base64.getEncoder().encode(readBuf)
Base64类中源码方法如下:
/**
* Returns a {@link Encoder} that encodes using the
* <a href="#basic">Basic</a> type base64 encoding scheme.
*
* @return A Base64 encoder.
*/
public static Encoder getEncoder() {
return Encoder.RFC4648;
}
使用此种方式encode则采用如下方式计算长度:
public static Long getBase64Len(Long length) {
return (((4 * length / 3) + 3) & ~3);
}
两种方式的区别在于编码后的格式稍微有差异,具体区别大家可以找个相同的文件采用不同的方式编码后看看编码内容;
以下为使用中的示例代码中:
@Override
public void encodeSavePos(InputStream is, String outPath, Long pos) throws IOException {
RandomAccessFile randomAccessFile = new RandomAccessFile(outPath, "rw");
randomAccessFile.seek(pos);
byte[] buf = new byte[READ_BUFFER_SIZE];
int readLen;
byte[] readBuf;
byte[] base64Buf;
BufferedInputStream bis = new BufferedInputStream(is);
while (-1 != (readLen = bis.read(buf))) {
readBuf = Arrays.copyOf(buf, readLen);
base64Buf = Base64.getMimeEncoder().encode(readBuf);
randomAccessFile.write(base64Buf, 0, base64Buf.length);
}
bis.close();
randomAccessFile.close();
}