如何读取扩展名为.7z的文件中的内容

5
我想读取一个.7z压缩文件中的文件,但是不想将其解压到本地系统。但是在Java缓冲区中,我需要读取文件的所有内容。有没有办法做到这一点?如果可以,您能否提供示例代码?
场景:
主文件-TestFile.7z
TestFile.7z中的文件是First.xml、Second.xml和Third.xml。
我想读取First.xml而不解压它。

7zip有一个Java API用于读取7z文件:http://www.7-zip.org/sdk.html。 - Torben Rasmussen
2个回答

2
您可以使用Apache Commons Compress库。该库支持多种存档格式的打包和解包。要使用7z格式,您还需要将xz-1.4.jar放入类路径中。这里是XZ for Java sources。您可以从Maven Central Repository下载XZ binary
以下是一个读取7z存档内容的小例子。
public static void main(String[] args) throws IOException {
  SevenZFile archiveFile = new SevenZFile(new File("archive.7z"));
  SevenZArchiveEntry entry;
  try {
    // Go through all entries
    while((entry = archiveFile.getNextEntry()) != null) {
      // Maybe filter by name. Name can contain a path.
      String name = entry.getName();
      if(entry.isDirectory()) {
        System.out.println(String.format("Found directory entry %s", name));
      } else {
        // If this is a file, we read the file content into a 
        // ByteArrayOutputStream ...
        System.out.println(String.format("Unpacking %s ...", name));
        ByteArrayOutputStream contentBytes = new ByteArrayOutputStream();

        // ... using a small buffer byte array.
        byte[] buffer = new byte[2048];
        int bytesRead;
        while((bytesRead = archiveFile.read(buffer)) != -1) {
          contentBytes.write(buffer, 0, bytesRead);
        }
        // Assuming the content is a UTF-8 text file we can interpret the
        // bytes as a string.
        String content = contentBytes.toString("UTF-8");
        System.out.println(content);
      }
    }
  } finally {
    archiveFile.close();
  }
}

我已经按照这个例子进行了操作,实现非常容易,但是...... XZ库存在一个关键性的错误:如果存档包含超过65535个条目,则所有其他条目都无法读取,并显示IOException“校验和验证失败”。https://www.mail-archive.com/issues@commons.apache.org/msg108686.html 该错误尚未解决。 - Igor

1
尽管Apache Commons Compress库按照上述宣传工作,但我发现对于任何大文件来说,它的速度都过慢,我的文件大小约为1GB或更大。我不得不从Java中调用本机命令行7z.exe来处理我的大型图像文件,这至少快了10倍。
我使用的是jre1.7。或许在更高版本的jre中会有改善。

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