Open stefan-reich opened 1 year ago
This demo works well.
package demo;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import net.sf.sevenzipjbinding.*;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import net.sf.sevenzipjbinding.simple.ISimpleInArchive;
import net.sf.sevenzipjbinding.simple.ISimpleInArchiveItem;
public class ExtractItemsSimpleDemo {
public static void main(String[] args) {
String testPath = "your/path/";
RandomAccessFile randomAccessFile = null;
IInArchive inArchive = null;
try {
randomAccessFile = new RandomAccessFile("your/file", "r");
inArchive = SevenZip.openInArchive(null, // autodetect archive type
new RandomAccessFileInStream(randomAccessFile));
// Getting simple interface of the archive inArchive
ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();
System.out.println(" Hash | Size | Filename");
System.out.println("----------+------------+---------");
for (ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
final int[] hash = new int[] { 0 };
if (!item.isFolder()) {
String extractedObject = testPath + item.getPath();
Path pathToExtractedObject = Paths.get(extractedObject);
System.out.println("pathToExtractedObject is: " + pathToExtractedObject);
Files.createDirectories(pathToExtractedObject.getParent());
FileOutputStream fos = new FileOutputStream(extractedObject);
ExtractOperationResult result;
final long[] sizeArray = new long[1];
result = item.extractSlow(new ISequentialOutStream() {
public int write(byte[] data) throws SevenZipException {
hash[0] ^= Arrays.hashCode(data); // Consume data
sizeArray[0] += data.length;
try {
System.err.println("item: " + item.getPath() +", date length: " + data.length);
fos.write(data,0,data.length);
} catch (Exception e) {
System.err.println("Error: " + e);
}
return data.length; // Return amount of consumed data
}
});
fos.close();
if (result == ExtractOperationResult.OK) {
System.out.println(String.format("%9X | %10s | %s",
hash[0], sizeArray[0], item.getPath()));
} else {
System.err.println("Error extracting item: " + result);
}
}
}
} catch (Exception e) {
System.err.println("Error occurs: " + e);
} finally {
if (inArchive != null) {
try {
inArchive.close();
} catch (SevenZipException e) {
System.err.println("Error closing archive: " + e);
}
}
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e) {
System.err.println("Error closing file: " + e);
}
}
}
}
}
Hi, maybe I just didn't see it - is there a simple example for how to extract a whole archive into a directory? All the callbacks I apparently have to implement look a bit complicated. Also I want to avoid calling extractSlow which, I'm guessing, is expanding streams multiple times needlessly to find just the one requested file.
Thanks in advance