7

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.

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
Alex
  • 91
  • 1
  • 3

2 Answers2

7

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.

rodion
  • 14,729
  • 3
  • 53
  • 55
  • This is expected, per Ant's code itself: https://svn.apache.org/viewvc/ant/core/trunk/src/main/org/apache/tools/ant/types/resources/BZip2Resource.java?view=markup#l71 – François Beausoleil Jun 03 '13 at 15:27
3

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();

    }
Fred37b
  • 822
  • 2
  • 10
  • 29