如何读取 .7z 扩展文件中文件的内容 [英] How To read contents for file which is in .7z extension file

查看:24
本文介绍了如何读取 .7z 扩展文件中文件的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to read a file which is in .7z zipped file. I do not want it to be extracted on to local system. But in Java Buffer it self I need to read all contents of file. Is there any way to this? If yes can you provide example of the code to do that?

场景:

主文件- TestFile.7z

TestFile.7z 里面的文件是 First.xml, Second.xml, Third.xml

我想在不解压的情况下阅读First.xml.

I want to read First.xml without unzipping it.

推荐答案

您可以使用 Apache公共压缩库.该库支持对多种归档格式进行打包和解包.要使用 7z 格式,您还必须将 xz-1.4.jar 放入类路径.以下是 Java 源代码的 XZ.您可以从 Maven 中央存储库下载 XZ 二进制文件.

You can use the Apache Commons Compress library. This library supports packing and unpacking for several archive formats. To use 7z format you also have to put xz-1.4.jar into the classpath. Here are the XZ for Java sources. You can download the XZ binary from Maven Central Repository.

这是一个读取 7z 存档内容的小例子.

Here is a small example to read the contents of a 7z archive.

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();
  }
}

这篇关于如何读取 .7z 扩展文件中文件的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆