我尝试压缩超过100Mb的大视频文件。
public static void compress(File input, File output) throws IOException {
InputStream fis = new FileInputStream(input);
byte[] bFile = IOUtils.toByteArray(fis);
FileOutputStream fos = new FileOutputStream(output);
GZIPOutputStream gzipStream = new GZIPOutputStream(fos);
try {
gzipStream.write(bFile);
// IOUtils.copy(fis, gzipStream);
} finally {
gzipStream.close();
fis.close();
fos.close();
}
}每次我忘记记忆错误的时候。
发布于 2014-04-24 18:24:58
您应该逐步复制数据,这样就不会耗尽内存。
public static void compress(File input, File output) throws IOException {
try(InputStream in = new FileInputStream(input);
OutputStream out = new GZIPOutputStream(new FileOutputStream(output))) {
byte[] bytes = new byte[4096];
for(int len; (len = in.read(bytes)) > 0; )
out.write(bytes, 0, len);
}
}这将一次使用大约4 KB作为缓冲区,而不考虑文件的大小。(我怀疑GZIP使用大致相同的方法来完成它的工作)
发布于 2020-02-11 14:35:31
您可以使用:
IOUtils.copy(inputStream, outputStream);它将自己处理字节缓冲区。您不需要显式创建byte[],因为在大容量的情况下,您通过使用以下命令在内存中加载大容量字节数组:
IOUtils.toByteArray(fis); //这会将整个字节数组加载到内存中。
https://stackoverflow.com/questions/23265857
复制相似问题