Search code examples
javatruezip

How to get bytes of TFile using TrueZip API (without extracting) in Java


How can I read binary file (get byte array) inside zip archive? I'm using TrueZip.

My example:

import de.schlichtherle.truezip.file.TFile;
import java.util.HashMap;

public class Archive {
     private final TFile archive;
     // String in HashMap represents filename ( eg. MyTextFile.txt )
     private final HashMap<String, TFile> entries = new HashMap<>();

public Archive( String path ) {
    this.archive = new TFile(path);
    this.listEntries( archive.getAbsolutePath() );
}

// lists all files
private void listEntries( String pathToZipFile ) {
    TFile archive = new TFile( pathToZipFile );
    for ( TFile listFile : archive.listFiles() ) {
        if ( listFile.isDirectory() ) {
            listEntries(listFile.getAbsolutePath());
        } else {
            entries.put(listFile.getName(), listFile);
        }
    }
}

public byte[] getBytes( String key ) {
     TFile file = entries.get(key);
     // ...

}

I am looking for something like this but for TFile / TPath:

Files.readAllBytes( file.toPath() );

Solution

  • There is a TPath class (https://truezip.java.net/truezip-path/) and an adaptor for the NIO.2 file system, so its very easy:

    Path path = new TPath(new URI("http://acme.com/download/everything.zip/README.TXT"));
    byte[] bytes= Files.readAllBytes(path);