龙珠

修炼自己与发现世界

bz2:Java中读取bz2文件数据

下载的数据中很多是.bz2格式的,里面包含一个文本文件,一个个解压出来耗时间耗空间(我400M的bz2文件解压后2.5G),也麻烦。

在网上查找如何在Java中解压缩bz2文件,国内资料有用的基本没有,百度和谷歌搜索结果第一条都是这个:在java语言中如何读取bz2文件中的数据。

ZipInputStream可以读取zip文件,构造的参数是FileInputStream等

          |----getNextEntry() :可以得到zip文件中的一个子文件,再次调用得到下一个子文件

ZipEntry类中的getName():可以得到子文件的文件名

但其中给出的是解压缩zip文件的,bz2不能用。

还是stackoverflow网站好,搜英文就有答案。在Uncompress BZIP2 archiveJava - Read BZ2 file and uncompress/parse on the fly

不过我使用第二篇中的org.apache.tools.bzip2.CBZip2InputStream并没有效果,会出现nullPointerException,查了一下,有人说是jar包内文件需要修改。

最后使用第一篇中的BZip2CompressorInputStream 实现,需要去官网Apache Commons Compress下载jar包,官网给的例子是:

FileInputStream fin = new FileInputStream("archive.tar.bz2");

BufferedInputStream in = new BufferedInputStream(fin);

FileOutputStream out = new FileOutputStream("archive.tar");

BZip2CompressorInputStream bzIn = new BZip2CompressorInputStream(in);

final byte[] buffer = new byte[buffersize];

int n = 0;

while (-1 != (n = bzIn.read(buffer))) {

   out.write(buffer, 0, n);

}

out.close();

bzIn.close();

需要注意的是,由于BZipCompressorOutputStream 很占内存,因此在不需要的时候一定要及时close掉。

“Note that BZipCompressorOutputStream keeps hold of some big data structures in memory. While it is true recommended for any stream that you close it as soon as you no longer needed, this is even more important for BZipCompressorOutputStream.”

参考资料:

  1. 在java语言中如何读取bz2文件中的数据。

  2. Uncompress BZIP2 archive

  3. Java - Read BZ2 file and uncompress/parse on the fly

  4. Apache Commons Compress