在下面的代碼中,如果我給 (Apache) Commons 壓縮一個幾 GB 大小的單個文件,它將崩潰,因為它耗盡了我的所有內存。我可以讓它一次讀取然后寫入文件的一小部分嗎?我一直在研究分塊,但我不知道如何做到這一點,以便我可以在將文件寫入 .tar 格式后將文件重新組合在一起。處理這里任何大小的支持文件的最佳方法是什么?FileOutputStream fileOutputStream = new FileOutputStream("output.tar");BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);GzipCompressorOutputStream gzipOutputStream = new GzipCompressorOutputStream(bufferedOutputStream);TarArchiveOutputStream tarArchiveOutputStream = new TarArchiveOutputStream(gzipOutputStream)) {tarArchiveOutputStream.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_POSIX);tarArchiveOutputStream.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);File currentFile = new File("Huge_MultiGB_File.txt");String relativeFilePath = currentFile.getPath();TarArchiveEntry tarEntry = new TarArchiveEntry(currentFile, relativeFilePath);tarEntry.setSize(currentFile.length());tarArchiveOutputStream.putArchiveEntry(tarEntry);tarArchiveOutputStream.write(IOUtils.toByteArray(new FileInputStream(currentFile)));tarArchiveOutputStream.closeArchiveEntry();
1 回答

森林海
TA貢獻2011條經驗 獲得超2個贊
您必須寫入文件的一小部分并將其寫入循環中的輸出,而不是首先將整個文件讀取到內存中IOUtils
它或多或少是這樣完成的:
FileInputStream source=new FileInputStream(....somefile);
tarArchiveOutputStream; prepared to w writing
byte[] buff = new byte[1024*10]; //10kb buff
int numBytesRead = -1; //number of bytes read
while(( numBytesRead = source.read(buff)) > 0 ) {
// while source has bytes, read from source and write
// the same number of bytes to the tar outputstream
tarArchiveOutputStream.write(buff, 0, numBytesRead);
}
}
添加回答
舉報
0/150
提交
取消