看了太多计算的方式,也验证了下,这里个人总结一下,此处主要针对 java.util.base64 来总结一下:
方式一
base64.getmimeencoder().encode(readbuf)
base64类中源码方法如下:
/**
* returns a {@link encoder} that encodes using the
* <a href="#mime" rel="external nofollow" >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" rel="external nofollow" >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();
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论