Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extracting files with zip4j temporarily. (Extracted for reading but not visible in cache file)

I am working with zip4j & packing & extracting work but i'm curious on how to just extract the file without putting the files in the cache.

Here is some code i found on another thread:

public static void main() {
    String source = "C:\\Users\\gamecaching\\Cache.zip";
    String destination = "C:\\Users\\gamecaching\\";
    String password = "mypassword";

    try {
        ZipFile zipFile = new ZipFile(source);
        if (zipFile.isEncrypted()) {
            zipFile.setPassword(password);
        }
        zipFile.extractAll(destination);
    } catch (ZipException e) {
        e.printStackTrace();
    }
}

How do I get it to only extract while the program is running(&& extracted files not visible in directory) & delete after the program has exited.

like image 705
Ryan Avatar asked Sep 24 '13 06:09

Ryan


3 Answers

After you create a ZipFile

ZipFile zipFile = new ZipFile(source);

you can loop through each File in the zip file like this:

ArrayList fileHeaderList = zipFile.getFileHeaders();

For each ZipFile:

for (int i = 0; i < fileHeaderList.size(); i++) {
    FileHeader fileHeader = (FileHeader)fileHeaderList.get(i);

Then, you can get the inputStream by doing this

is = zipFile.getInputStream(fileHeader);

Now you have the InputStream to read from.

A comprehensive example to work with Streams is below (taken from Zip4j examples package.) Although this example still writes to a file, but it demonstrates the use of streams with the zip file. I suggest having a look at a few more examples in the examples package.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.io.ZipInputStream;
import net.lingala.zip4j.model.FileHeader;
import net.lingala.zip4j.unzip.UnzipUtil;

/**
 * Example demonstrating the use of InputStreams to extract files from the
 * ZipFile
 */
public class ExtractAllFilesWithInputStreams {

    private final int BUFF_SIZE = 4096;

    public ExtractAllFilesWithInputStreams() {
        ZipInputStream is = null;
        OutputStream os = null;
        try {
            // Initiate the ZipFile
            ZipFile zipFile = new ZipFile(
                "C:\\ZipTest\\ExtractAllFilesWithInputStreams.zip");
            String destinationPath = "c:\\ZipTest";
            // If zip file is password protected then set the password
            if (zipFile.isEncrypted()) {
                zipFile.setPassword("password");
            }
            // Get a list of FileHeader. FileHeader is the header information
            // for all the files in the ZipFile
            List fileHeaderList = zipFile.getFileHeaders();
            // Loop through all the fileHeaders
            for (int i = 0; i < fileHeaderList.size(); i++) {
                FileHeader fileHeader = (FileHeader) fileHeaderList.get(i);
                if (fileHeader != null) {
                    // Build the output file
                    String outFilePath = destinationPath
                        + System.getProperty("file.separator")
                        + fileHeader.getFileName();
                    File outFile = new File(outFilePath);
                    // Checks if the file is a directory
                    if (fileHeader.isDirectory()) {
                        // This functionality is up to your requirements
                        // For now I create the directory
                        outFile.mkdirs();
                        continue;
                    }
                    // Check if the directories(including parent directories)
                    // in the output file path exists
                    File parentDir = outFile.getParentFile();
                    if (!parentDir.exists()) {
                        parentDir.mkdirs();
                    }
                    // Get the InputStream from the ZipFile
                    is = zipFile.getInputStream(fileHeader);
                    // Initialize the output stream
                    os = new FileOutputStream(outFile);
                    int readLen = -1;
                    byte[] buff = new byte[BUFF_SIZE];
                    // Loop until End of File and write the contents to the
                    // output stream
                    while ((readLen = is.read(buff)) != -1) {
                        os.write(buff, 0, readLen);
                    }
                    // Please have a look into this method for some important
                    // comments
                    closeFileHandlers(is, os);
                    // To restore File attributes (ex: last modified file time,
                    // read only flag, etc) of the extracted file, a utility
                    // class can be used as shown below
                    UnzipUtil.applyFileAttributes(fileHeader, outFile);
                    System.out.println("Done extracting: "
                        + fileHeader.getFileName());
                } else {
                    System.err.println("fileheader is null. Shouldn't be here");
                }
            }
        } catch (ZipException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                closeFileHandlers(is, os);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void closeFileHandlers(ZipInputStream is, OutputStream os)
            throws IOException {
        // Close output stream
        if (os != null) {
            os.close();
            os = null;
        }
        // Closing inputstream also checks for CRC of the the just extracted
        // file. If CRC check has to be skipped (for ex: to cancel the unzip
        // operation, etc) use method is.close(boolean skipCRCCheck) and set the
        // flag, skipCRCCheck to false
        // NOTE: It is recommended to close outputStream first because Zip4j
        // throws an exception if CRC check fails
        if (is != null) {
            is.close();
            is = null;
        }
    }

    public static void main(String[] args) {
        new ExtractAllFilesWithInputStreams();
    }
}
like image 164
Srikanth Reddy Lingala Avatar answered Nov 14 '22 21:11

Srikanth Reddy Lingala


an example derived from ExtractAllFilesWithInputStreams:

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.io.ZipInputStream;
import net.lingala.zip4j.model.FileHeader;

public class StackoverFlow18974389 {

    public static void main(String[] args) {
        Map<String, InputStream> inMemoryFiles = new HashMap<>();
        try {
            ZipFile zipFile = new ZipFile("test.zip");
            List fileHeaderList = zipFile.getFileHeaders();
            for (int i = 0; i < fileHeaderList.size(); i++) {
                FileHeader fileHeader = (FileHeader) fileHeaderList.get(i);
                ZipInputStream is = zipFile.getInputStream(fileHeader);
                int uncompressedSize = (int) fileHeader.getUncompressedSize();
                OutputStream os = new ByteArrayOutputStream(uncompressedSize);
                int bytesRead;
                byte[] buffer = new byte[4096];
                while ((bytesRead = is.read(buffer)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }
                byte[] uncompressedBytes = ((ByteArrayOutputStream) os).toByteArray();
                inMemoryFiles.put(fileHeader.getFileName(), new ByteArrayInputStream(uncompressedBytes));
                is.close();
            }
        } catch (ZipException | IOException ex) {
            ex.printStackTrace(System.err);
        }
        // very simple example how to access the files from the map
        for (String fileName : inMemoryFiles.keySet()) {
            System.out.print("in memory file: " + fileName);
            InputStream is = new BufferedInputStream(inMemoryFiles.get(fileName));
            long length = 0;
            try {
                while (is.read() != -1) {
                    length++;
                }
            } catch (IOException ex) {
                ex.printStackTrace(System.err);
            }
            System.out.println(" size. " + length);
        }
    }
}
like image 32
SubOptimal Avatar answered Nov 14 '22 22:11

SubOptimal


To read a concrete entry of a zip file use: zipFile.getInputStream(FileHeader). To read all entries:

for (FileHeader entry: zipFile:getFileHeaders()){
    zipFile.getInputStream(FileHeader);
}
like image 1
agad Avatar answered Nov 14 '22 22:11

agad