简体   繁体   中英

How To read contents for file which is in .7z extension file

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?

Scenario:

Main File- TestFile.7z

Files inside TestFile.7z are First.xml, Second.xml, Third.xml

I want to read First.xml without unzipping it.

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.

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

While the Apache Commons Compress library works as advertized above I've found it to be unusably slow for files of any substantial size -- mine were around a GB or more. I had to call a native command line 7z.exe from java for my large image files which was at least 10 times faster.

I used jre1.7. Maybe things will improve for higher versions of the jre.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM