Hey guys, in the previous post we discussed about reading the contents of Zip file without unzipping using ZipFile
. In this post, we will discuss about reading the contents of .7z
file without unzipping it. so let’s begin…
So in order to read the contents of .7z
file, we will use SevenZFile
from apache commons compress, along with we will use one more supporting jar which XZ for java.
Table of Contents
Little about XZ for Java
This aims to be a complete implementation of XZ data compression in pure Java. Single-threaded streamed compression and decompression and random access decompression have been fully implemented. Threading is planned but it is unknown when it will be implemented.
let’s look at an example..
import java.io.File;
import java.io.IOException;
import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
import org.apache.commons.compress.archivers.sevenz.SevenZFile;
public class SevenZFileTest {
public static void main(String[] args) throws IOException {
try {
SevenZFile sevenZFile = new SevenZFile(new File("D://test.7z"));
SevenZArchiveEntry entry;
while ((entry = sevenZFile.getNextEntry()) != null) {
System.out.println("Name: " + entry.getName());
System.out.println("Size : " + entry.getSize());
System.out.println("--------------------------------");
}
sevenZFile.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
So here we will pass the file to the constructor of SevenZFile
and then on the sevenz file object we will call getNextEntry()
, this will gives the next archive entry in the 7z archive, then we check for file exists, if it exists, we will get the file name and file size. There are plenty other methods available, you can explore in case if you want.
It produces the following output..
Name: Olympus_design_Update_02_Guide_Doc.pdf
Size : 1069667
--------------------------------
Name: changes 24_07.pptx
Size : 3162574
--------------------------------
Name: Bug List on ingestion_updated.xlsx
Size : 17841
--------------------------------
Constructors
SevenZFile(File file)
: Reads a file as unencrypted 7z archive
Ex: new SevenZFile(new File(“D://test.7z”));
Methods
getEntries(): Iterable<SevenZArchiveEntry>
– Returns meta-data of all archive entries.getNextEntry
(): SevenZArchiveEntry
– Returns the next Archive Entry in this archive.read(): int
– Reads data into an array of bytes.
SevenZArhiveEntry methods
getName(): String
– Get this entry’s name.getSize(): long
– Get this entry’s file size.isDirectory(): boolean
– Return whether or not this entry represents a directory.
That’s it for this post, i will see you in the next post.