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.
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.
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.
BZ2 is a lossless data compression format that lets users retrieve the original data of compressed files.
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With