在Java中将tar.gz文件提取到内存中

5

我正在使用Apache Compress库来读取.tar.gz文件,就像这样:

    final TarArchiveInputStream tarIn = initializeTarArchiveStream(this.archiveFile);
    try {
        TarArchiveEntry tarEntry = tarIn.getNextTarEntry();
        while (tarEntry != null) {
            byte[] btoRead = new byte[1024];
            BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(destPath)); //<- I don't want this!
            int len = 0;
            while ((len = tarIn.read(btoRead)) != -1) {
                bout.write(btoRead, 0, len);
            }
            bout.close();
            tarEntry = tarIn.getNextTarEntry();
        }
        tarIn.close();
    }
    catch (IOException e) {
        e.printStackTrace();
    }

有没有可能不将它提取到单独的文件中,而是以某种方式在内存中读取它?也许可以读入一个巨大的字符串或类似的东西吗?


你为什么想要这样做? - Miserable Variable
3个回答

9
您可以用ByteArrayOutputStream替换文件流。

也就是说,将这个:

BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(destPath)); //<- I don't want this!

通过这种方式:

ByteArrayOutputStream bout = new ByteArrayOutputStream();

在关闭后,使用获取字节。

4
可以不将其提取到单独的文件中,而是以某种方式将其读入内存中吗?也许是读入一个巨大的字符串或其他什么东西?
可以。只需用写入到ByteArrayOutputStream或一系列这样的流的代码替换打开文件并将其写入的内部循环中的代码。
从TAR(如此)读取的数据的自然表示形式将是字节/字节数组。如果字节是正确编码的字符,并且您知道正确的编码,则可以将它们转换为字符串。否则,最好将数据保留为字节。(如果尝试将非文本数据转换为字符串,或者使用错误的字符集/编码进行转换,则可能会损坏它……无法恢复。)
显然,您需要自己考虑其中的一些问题,但基本思路应该可行……前提是您拥有足够的堆空间。

0
将btoread的值复制到一个字符串中,例如
String s = String.valueof(byteVar);
然后不断将字节值添加到该字符串,直到文件结尾为止。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接