在做项目的时候遇到需要将文件转为base64编码,并存储在文件中。
在将文件转为base64编码是会将文件读入内存,进行base64编码,输出到文件中。代码入下:
1 2 3 4 5 6 7 8 9 10 | FileInputStream stream = new FileInputStream("D:\\桌面\\程序员-第4版.pdf");
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
byte[] b = new byte[1024];
int n;
while ((n = stream.read(b)) != -1) {
out.write(b, 0, n);
}
stream.close();
out.close();
System.out.println(new String(Base64.encodeBase64(out.toByteArray())));
|
但是大文件在进行base64编码的时候就会遇到OOM(OOM为out of memory的简称,称之为内存溢出)。
产生OOM的原因:
由于3个常规字符可以转换为4个base64编码字符,所以使用3的公倍数作为缓冲区大小。
所以在对大文件进行base64编码时可以采用分段编码,进行输出。代码入下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | ByteArrayOutputStream os1 = new ByteArrayOutputStream();
InputStream file1 = new FileInputStream("D:\\桌面\\程序员-第4版.pdf");
byte[] byteBuf = new byte[3 * 1024 * 1024];
byte[] base64ByteBuf;
int count1;
while ((count1 = file1.read(byteBuf)) != -1) {
if (count1 != byteBuf.length) {
byte[] copy = Arrays.copyOf(byteBuf, count1);
base64ByteBuf = Base64.encodeBase64(copy);
} else {
base64ByteBuf = Base64.encodeBase64(byteBuf);
}
os1.write(base64ByteBuf, 0, base64ByteBuf.length);
os1.flush();
}
file1.close();
System.out.println(os1.toString());
|
以上代码是将编码后的数据输出至控制台。其实最好是将文件分段进行编码,分段输出,这样不管文件多大,都可以进行编码,并且不会OOM。以下是将文件输出至txt文档中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | ByteArrayOutputStream os1 = new ByteArrayOutputStream();
InputStream file1 = new FileInputStream("D:\\桌面\\程序员-第4版.pdf");
byte[] byteBuf = new byte[3 * 1024 * 1024];
byte[] base64ByteBuf;
int count1;
File file = new File("D:\\1.txt");
while ((count1 = file1.read(byteBuf)) != -1) {
if (count1 != byteBuf.length) {
byte[] copy = Arrays.copyOf(byteBuf, count1);
base64ByteBuf = Base64.encodeBase64(copy);
} else {
base64ByteBuf = Base64.encodeBase64(byteBuf);
}
FileUtils.writeByteArrayToFile(file, base64ByteBuf, true);
os1.flush();
}
file1.close();
|