Java:Bzip2库

Java:Bzip2库,java,bzip2,Java,Bzip2,我需要创建Bzip2档案。 从“ApacheAnt”下载的bzip2库 I use class CBZip2OutputStream: String s = ..... CBZip2OutputStream os = new CBZip2OutputStream(fos); os.write(s.getBytes(Charset.forName("UTF-8"))); os.flush(); os.

我需要创建Bzip2档案。 从“ApacheAnt”下载的bzip2库

I use class CBZip2OutputStream: 
String s = .....
CBZip2OutputStream os = new CBZip2OutputStream(fos);
                os.write(s.getBytes(Charset.forName("UTF-8")));
                os.flush();
                os.close();
(我没有找到任何示例如何使用它,所以我决定以这种方式使用它)


但它会在磁盘上创建一个损坏的存档

在写入内容之前,您必须添加BZip2头(两个字节:'B','Z'):

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

然后,例如,您可以在*nix系统上使用
cat compressed.bz2 | bunzip2>uncompressed.txt
提取bzipped文件的内容。

我没有找到一个示例,但最终我了解了如何使用CBZip2OutputStream,因此这里有一个:

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

    }

根据Ant的代码本身,这是意料之中的: