首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java: Bzip2库

Java: Bzip2库
EN

Stack Overflow用户
提问于 2010-12-11 13:52:51
回答 2查看 4.4K关注 0票数 7

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

代码语言:javascript
复制
I use class CBZip2OutputStream: 
String s = .....
CBZip2OutputStream os = new CBZip2OutputStream(fos);
                os.write(s.getBytes(Charset.forName("UTF-8")));
                os.flush();
                os.close();

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

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

EN

回答 2

Stack Overflow用户

发布于 2010-12-11 16:16:00

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

代码语言:javascript
复制
//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文件的内容。

票数 7
EN

Stack Overflow用户

发布于 2012-10-22 21:36:33

我还没有找到一个例子,但最后我明白了如何使用CBZip2OutputStream,所以这里有一个例子:

代码语言:javascript
复制
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();

    }
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4415429

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档