简体   繁体   中英

How to compress multiple file with CBZip2OutputStream

I use CBZip2OutputStream for create a compressed bzip file. It works.

But I want to compress several files in one bzip file but without using tar archive.

If I have file1, file2, file3, I want them in files.bz2 not in an archive files.tar.bz2.

It is possible ?

BZip2 is only a compressor for single files so it is not possible to put several files in a Bzip2 file without putting them into an archive file first.

You could put you own file start and end markers into the output stream but it would be better to use a standard archive format.

Apache Commons has TarArchiveOutputStream (and TarArchiveInputStream ) which would be useful here.

I understand so I use a package with a TarOutputStream class like that :

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");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM