如何使用CBZip2OutputStream压缩多个文件

时间:2012-10-23 15:37:06

标签: java stream bzip2

我使用CBZip2OutputStream来创建压缩的bzip文件。它有效。

但我想在一个bzip文件中压缩几个文件但不使用tar存档。

如果我有file1,file2,file3,我希望它们在files.bz2中而不是存档files.tar.bz2。

有可能吗?

2 个答案:

答案 0 :(得分:1)

BZip2 is only a compressor for single files所以不能将多个文件放在Bzip2文件中而不将它们放入存档文件中。

您可以将自己的文件开始和结束标记放入输出流中,但最好使用标准存档格式。

Apache Commons has TarArchiveOutputStream(和TarArchiveInputStream)在这里很有用。

答案 1 :(得分:0)

我理解所以我使用了一个包含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");
    }
}