7

我需要创建 Bzip2 存档。从“Apache ant”下载的 bzip2 库。

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

(我没有找到任何如何使用它的示例,所以我决定以这种方式使用它)

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

4

2 回答 2

7

您必须在写入内容之前添加 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 ...

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

于 2010-12-11T08:16:00.303 回答
3

我还没有找到一个例子,但最后我明白了如何使用 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();

    }
于 2012-10-22T13:36:33.450 回答