/*
 * [TestZipReadRandom.java]
 *
 * Summary: Example to read the elements of a Zip file randomly by name lookup.
 *
 * Copyright: (c) 2009-2017 Roedy Green, Canadian Mind Products, http://mindprod.com
 *
 * Licence: This software may be copied and used freely for any purpose but military.
 *          http://mindprod.com/contact/nonmil.html
 *
 * Requires: JDK 1.8+
 *
 * Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/
 *
 * Version History:
 *  1.0 2008-06-06
 */
package com.mindprod.example;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import static java.lang.System.*;
/**
 * Example to read the elements of a Zip file randomly by name lookup.
 *
 * @author Roedy Green, Canadian Mind Products
 * @version 1.0 2008-06-06
 * @since 2008-06-06
 */
public final class TestZipReadRandom
    {
    /**
     * read the elements of a Zip file sequentially.
     *
     * @param args not used
     *
     * @throws java.io.IOException if problems writing file a.zip
     */
    public static void main( String[] args ) throws IOException
        {
        // specify the name of the zip we are going to read
        final String zipFileName = "in.zip";
        // specify internal directory structure and file name to read from zip.
        final String elementName = "com/mindprod/batik/run.bat";
        // specify the name of the directory where extracted data will go.
        final String targetdir = "targetdir";
        // look up that entry in the zip
        final ZipFile zip = new ZipFile( zipFileName );
        final ZipEntry entry = zip.getEntry( elementName );
        // length should be ok, even for stream-created zips and jars.
        final int fileLength = ( int ) entry.getSize();
        final byte[] wholeFile = new byte[ fileLength ];
        // read element contents.
        final InputStream is = zip.getInputStream( entry );
        final int bytesRead = is.read( wholeFile, 0, fileLength );
        // checking bytesRead, and repeating if you don't get item all is not shown.
        out.println( bytesRead + " bytes read from " + elementName );
        // write contents of element from RAM to a file.
        // Where we will put the external file.
        final File elementFile = new File( targetdir, elementName );
        // make sure dirs exist to hold the external file we are about to create.
        //noinspection ResultOfMethodCallIgnored
        elementFile.getParentFile().mkdirs();
        final FileOutputStream fos = new FileOutputStream( elementFile );
        fos.write( wholeFile, 0, fileLength );
        fos.close();
        elementFile.setLastModified( entry.getTime() );
        // no need for a zip.closeEntry()
        zip.close();
        }
    }