Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Bzip2 library

Tags:

java

bzip2

I need to create Bzip2 archive. A downloaded bzip2 library from 'Apache ant'.

I use class CBZip2OutputStream: 
String s = .....
CBZip2OutputStream os = new CBZip2OutputStream(fos);
                os.write(s.getBytes(Charset.forName("UTF-8")));
                os.flush();
                os.close();

(I didn't find any example how to use it, so I decided to use it in this way)

But it creates a corrupted archive on the disk.

like image 873
Alex Avatar asked Dec 11 '10 05:12

Alex


People also ask

Which is better gzip or bzip2?

If you are looking at compress and decompress files at a quickly gzip is the best option. The bzip2 provides a better compression ratio and speed, but the decompression takes a longer time limit. Both gzip and bzip2 are popular options for the compression of files.

What is file extension bzip2?

August 2021) bzip2 is a free and open-source file compression program that uses the Burrows–Wheeler algorithm. It only compresses single files and is not a file archiver. It was developed by Julian Seward, and maintained by Mark Wielaard and Micah Snyder. bzip2.

Is bzip2 lossless?

BZ2 is a lossless data compression format that lets users retrieve the original data of compressed files.


2 Answers

You have to add BZip2 header (two bytes: 'B','Z') before writing the content:

//Write 'BZ' before compressing the stream
fos.write("BZ".getBytes());
//Write to compressed stream as usual
CBZip2OutputStream os = new CBZip2OutputStream(fos);
... the rest ...

Then, for instance, you can extract contents of your bzipped file with cat compressed.bz2 | bunzip2 > uncompressed.txt on a *nix system.

like image 50
rodion Avatar answered Sep 26 '22 06:09

rodion


I have not found an example but in the end I understood how to use CBZip2OutputStream so here is one :

public void createBZipFile() throws IOException{

        // file to zip
        File file = new File("plane.jpg");

        // fichier compresse
        File fileZiped= new File("plane.bz2");

        // Outputstream for fileZiped
        FileOutputStream fileOutputStream = new FileOutputStream(fileZiped);
        fileOutputStream.write("BZ".getBytes());

        // we getting the data in a byte array
        byte[] fileData = getArrayByteFromFile(file);

        CBZip2OutputStream bzip = null;

        try{
            bzip = new CBZip2OutputStream(fileOutputStream );

            bzip.write(fileData, 0, fileData.length);
            bzip.flush() ;
            bzip.close();  

        }catch (IOException ex) {

            ex.printStackTrace();
        }



        fos.close();

    }
like image 45
Fred37b Avatar answered Sep 24 '22 06:09

Fred37b