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

时间:2014-02-24 11:40:07

标签: java xml

我想读取一个.7z压缩文件的文件。我不希望它被提取到本地系统。但是在Java Buffer中我自己需要读取文件的所有内容。这有什么办法吗?如果是,您可以提供代码示例吗?

情景:

主文件 - TestFile.7z

TestFile.7z内的文件为First.xml, Second.xml, Third.xml

我希望在不解压缩的情况下阅读First.xml

3 个答案:

答案 0 :(得分:1)

您可以使用Apache Commons Compress library。该库支持多种存档格式的打包和解包。要使用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();
  }
}

答案 1 :(得分:1)

虽然Apache Commons Compress库的工作方式如上所述,但我发现它对于任何大小的文件都非常慢 - 我的大约是GB或更多。我不得不从java调用本机命令行7z.exe来获取我的大图像文件,其速度至少快10倍。

我使用了jre1.7。也许对于更高版本的jre,事情会有所改善。

答案 2 :(得分:0)

7zip有一个用于读取7z文件的java API:http://www.7-zip.org/sdk.html

相关问题