如何使用 CBZip2OutputStream 压缩多个文件
Posted
技术标签:
【中文标题】如何使用 CBZip2OutputStream 压缩多个文件【英文标题】:How to compress multiple file with CBZip2OutputStream 【发布时间】:2012-10-23 15:37:06 【问题描述】:我使用 CBZip2OutputStream 创建一个压缩的 bzip 文件。它有效。
但我想在一个 bzip 文件中压缩多个文件,但不使用 tar 存档。
如果我有 file1、file2、file3,我希望它们在 files.bz2 中,而不是在存档 files.tar.bz2 中。
有可能吗?
【问题讨论】:
【参考方案1】:BZip2 is only a compressor for single files 因此,如果不先将多个文件放入存档文件,就无法将多个文件放入 Bzip2 文件中。
您可以将自己的文件开始和结束标记放入输出流,但最好使用标准存档格式。
Apache Commons has TarArchiveOutputStream
(和TarArchiveInputStream
)在这里很有用。
【讨论】:
【参考方案2】:我明白了,所以我使用了一个带有 TarOutputStream 类的包:
public void makingTarArchive(File[] inFiles, String inPathName) throws IOException
StringBuilder stringBuilder = new StringBuilder(inPathName);
stringBuilder.append(".tar");
String pathName = stringBuilder.toString() ;
// Output file stream
FileOutputStream dest = new FileOutputStream(pathName);
// Create a TarOutputStream
TarOutputStream out = new TarOutputStream( new BufferedOutputStream( dest ) );
for(File f : inFiles)
out.putNextEntry(new TarEntry(f, f.getName()));
BufferedInputStream origin = new BufferedInputStream(new FileInputStream( f ));
int count;
byte data[] = new byte[2048];
while((count = origin.read(data)) != -1)
out.write(data, 0, count);
out.flush();
origin.close();
out.close();
dest.close();
File file = new File(pathName) ;
createBZipFile(file);
boolean success = file.delete();
if (!success)
System.out.println("can't delete the .tar file");
【讨论】:
以上是关于如何使用 CBZip2OutputStream 压缩多个文件的主要内容,如果未能解决你的问题,请参考以下文章