Example usage for java.util.zip ZipFile entries

List of usage examples for java.util.zip ZipFile entries

Introduction

In this page you can find the example usage for java.util.zip ZipFile entries.

Prototype

public Enumeration<? extends ZipEntry> entries() 

Source Link

Document

Returns an enumeration of the ZIP file entries.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    ZipFile zipFile = new ZipFile(new File("testfile.zip"), ZipFile.OPEN_DELETE);

    Enumeration zipEntries = zipFile.entries();

    while (zipEntries.hasMoreElements()) {
        System.out.println(((ZipEntry) zipEntries.nextElement()).getName());
    }/*w w w. j  a v a2 s .  c om*/
}

From source file:MainClass.java

public static void main(String[] args) {

    try {/*from   w ww .j av a2 s .co  m*/
        ZipFile zf = new ZipFile("your.zip");
        Enumeration e = zf.entries();
        while (e.hasMoreElements()) {
            ZipEntry ze = (ZipEntry) e.nextElement();
            String name = ze.getName();

            Date lastModified = new Date(ze.getTime());
            long uncompressedSize = ze.getSize();
            long compressedSize = ze.getCompressedSize();

            int method = ze.getMethod();

            if (method == ZipEntry.STORED) {
                System.out.println(name + " was stored at " + lastModified);
                System.out.println("with a size of  " + uncompressedSize + " bytes");
            } else if (method == ZipEntry.DEFLATED) {
                System.out.println(name + " was deflated at " + lastModified);
                System.out.println("from  " + uncompressedSize + " bytes to " + compressedSize
                        + " bytes, a savings of " + (100.0 - 100.0 * compressedSize / uncompressedSize) + "%");
            } else {
                System.out.println(name + " was compressed using an unrecognized method at " + lastModified);
                System.out.println("from  " + uncompressedSize + " bytes to " + compressedSize
                        + " bytes, a savings of " + (100.0 - 100.0 * compressedSize / uncompressedSize) + "%");
            }
        }
    } catch (IOException ex) {
        System.err.println(ex);
    }
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    ZipFile zf = new ZipFile("a.zip");
    Enumeration<? extends ZipEntry> files = zf.entries();

    while (files.hasMoreElements()) {
        ZipEntry ze = files.nextElement();

        System.out.println("Decompressing " + ze.getName());
        System.out.println(//from   w w w .ja v  a  2s. com
                "  Compressed Size: " + ze.getCompressedSize() + "  Expanded Size: " + ze.getSize() + "\n");

        BufferedInputStream fin = new BufferedInputStream(zf.getInputStream(ze));
        BufferedOutputStream fout = new BufferedOutputStream(new FileOutputStream(ze.getName()));

        int i;
        do {
            i = fin.read();
            if (i != -1)
                fout.write(i);
        } while (i != -1);

        fout.close();
        fin.close();
    }
    zf.close();
}

From source file:ZipCompress.java

public static void main(String[] args) throws IOException {
    FileOutputStream f = new FileOutputStream("test.zip");
    CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32());
    ZipOutputStream zos = new ZipOutputStream(csum);
    BufferedOutputStream out = new BufferedOutputStream(zos);
    zos.setComment("A test of Java Zipping");
    // No corresponding getComment(), though.
    for (int i = 0; i < args.length; i++) {
        System.out.println("Writing file " + args[i]);
        BufferedReader in = new BufferedReader(new FileReader(args[i]));
        zos.putNextEntry(new ZipEntry(args[i]));
        int c;/*from w w  w . j  a  v  a2  s.c  o  m*/
        while ((c = in.read()) != -1)
            out.write(c);
        in.close();
    }
    out.close();
    // Checksum valid only after the file has been closed!
    System.out.println("Checksum: " + csum.getChecksum().getValue());
    // Now extract the files:
    System.out.println("Reading file");
    FileInputStream fi = new FileInputStream("test.zip");
    CheckedInputStream csumi = new CheckedInputStream(fi, new Adler32());
    ZipInputStream in2 = new ZipInputStream(csumi);
    BufferedInputStream bis = new BufferedInputStream(in2);
    ZipEntry ze;
    while ((ze = in2.getNextEntry()) != null) {
        System.out.println("Reading file " + ze);
        int x;
        while ((x = bis.read()) != -1)
            System.out.write(x);
    }
    System.out.println("Checksum: " + csumi.getChecksum().getValue());
    bis.close();
    // Alternative way to open and read zip files:
    ZipFile zf = new ZipFile("test.zip");
    Enumeration e = zf.entries();
    while (e.hasMoreElements()) {
        ZipEntry ze2 = (ZipEntry) e.nextElement();
        System.out.println("File: " + ze2);
        // ... and extract the data as before
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    ZipFile zipFile = new ZipFile(new File("testfile.zip"), ZipFile.OPEN_READ);
    System.out.println(zipFile.getComment());
    Enumeration zipEntries = zipFile.entries();

    while (zipEntries.hasMoreElements()) {
        System.out.println(((ZipEntry) zipEntries.nextElement()).getName());
    }//from w  w w  . j  a  va  2s  . c  o m
}

From source file:ZipFileViewer.java

public static void main(String[] arg) throws Exception {
    String zipFileName = arg[0];/*from  ww  w  . jav a 2 s. co  m*/
    List zipFileList = null;
    ZipFile zipFile = new ZipFile(zipFileName);
    Enumeration zipEntries = zipFile.entries();
    zipFileList = new ArrayList();
    while (zipEntries.hasMoreElements()) {
        zipFileList.add((ZipEntry) (zipEntries.nextElement()));
    }
    ZipFileViewer zipFileViewer = new ZipFileViewer(zipFileName, zipFileList);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    ZipFile zf = new ZipFile("ziptest.zip");

    // Get the enumeration for all zip entries and loop through them
    Enumeration<? extends ZipEntry> e = zf.entries();
    ZipEntry entry = null;//from   w w  w.  jav  a 2  s .  c  om

    while (e.hasMoreElements()) {
        entry = e.nextElement();

        // Get the input stream for the current zip entry
        InputStream is = zf.getInputStream(entry);

        /* Read data for the entry using the is object */

        // Print the name of the entry
        System.out.println(entry.getName());
    }

}

From source file:ZipCompare.java

public static void main(String[] args) {
    if (args.length != 2) {
        System.out.println("Usage: zipcompare [file1] [file2]");
        System.exit(1);/*from   w  ww .  j av  a 2s .  c om*/
    }

    ZipFile file1;
    try {
        file1 = new ZipFile(args[0]);
    } catch (IOException e) {
        System.out.println("Could not open zip file " + args[0] + ": " + e);
        System.exit(1);
        return;
    }

    ZipFile file2;
    try {
        file2 = new ZipFile(args[1]);
    } catch (IOException e) {
        System.out.println("Could not open zip file " + args[0] + ": " + e);
        System.exit(1);
        return;
    }

    System.out.println("Comparing " + args[0] + " with " + args[1] + ":");

    Set set1 = new LinkedHashSet();
    for (Enumeration e = file1.entries(); e.hasMoreElements();)
        set1.add(((ZipEntry) e.nextElement()).getName());

    Set set2 = new LinkedHashSet();
    for (Enumeration e = file2.entries(); e.hasMoreElements();)
        set2.add(((ZipEntry) e.nextElement()).getName());

    int errcount = 0;
    int filecount = 0;
    for (Iterator i = set1.iterator(); i.hasNext();) {
        String name = (String) i.next();
        if (!set2.contains(name)) {
            System.out.println(name + " not found in " + args[1]);
            errcount += 1;
            continue;
        }
        try {
            set2.remove(name);
            if (!streamsEqual(file1.getInputStream(file1.getEntry(name)),
                    file2.getInputStream(file2.getEntry(name)))) {
                System.out.println(name + " does not match");
                errcount += 1;
                continue;
            }
        } catch (Exception e) {
            System.out.println(name + ": IO Error " + e);
            e.printStackTrace();
            errcount += 1;
            continue;
        }
        filecount += 1;
    }
    for (Iterator i = set2.iterator(); i.hasNext();) {
        String name = (String) i.next();
        System.out.println(name + " not found in " + args[0]);
        errcount += 1;
    }
    System.out.println(filecount + " entries matched");
    if (errcount > 0) {
        System.out.println(errcount + " entries did not match");
        System.exit(1);
    }
    System.exit(0);
}

From source file:org.dspace.app.itemimport.ItemImport.java

public static void main(String[] argv) throws Exception {
    DSIndexer.setBatchProcessingMode(true);
    Date startTime = new Date();
    int status = 0;

    try {/*  www.  ja  va  2s.co  m*/
        // create an options object and populate it
        CommandLineParser parser = new PosixParser();

        Options options = new Options();

        options.addOption("a", "add", false, "add items to DSpace");
        options.addOption("b", "add-bte", false, "add items to DSpace via Biblio-Transformation-Engine (BTE)");
        options.addOption("r", "replace", false, "replace items in mapfile");
        options.addOption("d", "delete", false, "delete items listed in mapfile");
        options.addOption("i", "inputtype", true, "input type in case of BTE import");
        options.addOption("s", "source", true, "source of items (directory)");
        options.addOption("z", "zip", true, "name of zip file");
        options.addOption("c", "collection", true, "destination collection(s) Handle or database ID");
        options.addOption("m", "mapfile", true, "mapfile items in mapfile");
        options.addOption("e", "eperson", true, "email of eperson doing importing");
        options.addOption("w", "workflow", false, "send submission through collection's workflow");
        options.addOption("n", "notify", false,
                "if sending submissions through the workflow, send notification emails");
        options.addOption("t", "test", false, "test run - do not actually import items");
        options.addOption("p", "template", false, "apply template");
        options.addOption("R", "resume", false, "resume a failed import (add only)");
        options.addOption("q", "quiet", false, "don't display metadata");

        options.addOption("h", "help", false, "help");

        CommandLine line = parser.parse(options, argv);

        String command = null; // add replace remove, etc
        String bteInputType = null; //ris, endnote, tsv, csv, bibtex
        String sourcedir = null;
        String mapfile = null;
        String eperson = null; // db ID or email
        String[] collections = null; // db ID or handles

        if (line.hasOption('h')) {
            HelpFormatter myhelp = new HelpFormatter();
            myhelp.printHelp("ItemImport\n", options);
            System.out.println(
                    "\nadding items:    ItemImport -a -e eperson -c collection -s sourcedir -m mapfile");
            System.out.println(
                    "\nadding items from zip file:    ItemImport -a -e eperson -c collection -s sourcedir -z filename.zip -m mapfile");
            System.out
                    .println("replacing items: ItemImport -r -e eperson -c collection -s sourcedir -m mapfile");
            System.out.println("deleting items:  ItemImport -d -e eperson -m mapfile");
            System.out.println(
                    "If multiple collections are specified, the first collection will be the one that owns the item.");

            System.exit(0);
        }

        if (line.hasOption('a')) {
            command = "add";
        }

        if (line.hasOption('r')) {
            command = "replace";
        }

        if (line.hasOption('d')) {
            command = "delete";
        }

        if (line.hasOption('b')) {
            command = "add-bte";
        }

        if (line.hasOption('i')) {
            bteInputType = line.getOptionValue('i');
            ;
        }

        if (line.hasOption('w')) {
            useWorkflow = true;
            if (line.hasOption('n')) {
                useWorkflowSendEmail = true;
            }
        }

        if (line.hasOption('t')) {
            isTest = true;
            System.out.println("**Test Run** - not actually importing items.");
        }

        if (line.hasOption('p')) {
            template = true;
        }

        if (line.hasOption('s')) // source
        {
            sourcedir = line.getOptionValue('s');
        }

        if (line.hasOption('m')) // mapfile
        {
            mapfile = line.getOptionValue('m');
        }

        if (line.hasOption('e')) // eperson
        {
            eperson = line.getOptionValue('e');
        }

        if (line.hasOption('c')) // collections
        {
            collections = line.getOptionValues('c');
        }

        if (line.hasOption('R')) {
            isResume = true;
            System.out.println("**Resume import** - attempting to import items not already imported");
        }

        if (line.hasOption('q')) {
            isQuiet = true;
        }

        boolean zip = false;
        String zipfilename = "";
        String ziptempdir = ConfigurationManager.getProperty("org.dspace.app.itemexport.work.dir");
        if (line.hasOption('z')) {
            zip = true;
            zipfilename = sourcedir + System.getProperty("file.separator") + line.getOptionValue('z');
        }

        // now validate
        // must have a command set
        if (command == null) {
            System.out.println(
                    "Error - must run with either add, replace, or remove (run with -h flag for details)");
            System.exit(1);
        } else if ("add".equals(command) || "replace".equals(command)) {
            if (sourcedir == null) {
                System.out.println("Error - a source directory containing items must be set");
                System.out.println(" (run with -h flag for details)");
                System.exit(1);
            }

            if (mapfile == null) {
                System.out.println("Error - a map file to hold importing results must be specified");
                System.out.println(" (run with -h flag for details)");
                System.exit(1);
            }

            if (eperson == null) {
                System.out.println("Error - an eperson to do the importing must be specified");
                System.out.println(" (run with -h flag for details)");
                System.exit(1);
            }

            if (collections == null) {
                System.out.println("Error - at least one destination collection must be specified");
                System.out.println(" (run with -h flag for details)");
                System.exit(1);
            }
        } else if ("add-bte".equals(command)) {
            if (sourcedir == null) {
                System.out.println("Error - a source file containing items must be set");
                System.out.println(" (run with -h flag for details)");
                System.exit(1);
            }

            if (mapfile == null) {
                System.out.println("Error - a map file to hold importing results must be specified");
                System.out.println(" (run with -h flag for details)");
                System.exit(1);
            }

            if (eperson == null) {
                System.out.println("Error - an eperson to do the importing must be specified");
                System.out.println(" (run with -h flag for details)");
                System.exit(1);
            }

            if (collections == null) {
                System.out.println("Error - at least one destination collection must be specified");
                System.out.println(" (run with -h flag for details)");
                System.exit(1);
            }

            if (bteInputType == null) {
                System.out.println(
                        "Error - an input type (tsv, csv, ris, endnote, bibtex or any other type you have specified in BTE Spring XML configuration file) must be specified");
                System.out.println(" (run with -h flag for details)");
                System.exit(1);
            }
        } else if ("delete".equals(command)) {
            if (eperson == null) {
                System.out.println("Error - an eperson to do the importing must be specified");
                System.exit(1);
            }

            if (mapfile == null) {
                System.out.println("Error - a map file must be specified");
                System.exit(1);
            }
        }

        // can only resume for adds
        if (isResume && !"add".equals(command)) {
            System.out.println("Error - resume option only works with --add command");
            System.exit(1);
        }

        // do checks around mapfile - if mapfile exists and 'add' is selected,
        // resume must be chosen
        File myFile = new File(mapfile);

        if (!isResume && "add".equals(command) && myFile.exists()) {
            System.out.println("Error - the mapfile " + mapfile + " already exists.");
            System.out.println("Either delete it or use --resume if attempting to resume an aborted import.");
            System.exit(1);
        }

        // does the zip file exist and can we write to the temp directory
        if (zip) {
            File zipfile = new File(sourcedir);
            if (!zipfile.canRead()) {
                System.out.println("Zip file '" + sourcedir + "' does not exist, or is not readable.");
                System.exit(1);
            }

            if (ziptempdir == null) {
                System.out.println(
                        "Unable to unzip import file as the key 'org.dspace.app.itemexport.work.dir' is not set in dspace.cfg");
                System.exit(1);
            }
            zipfile = new File(ziptempdir);
            if (!zipfile.isDirectory()) {
                System.out.println("'" + ConfigurationManager.getProperty("org.dspace.app.itemexport.work.dir")
                        + "' as defined by the key 'org.dspace.app.itemexport.work.dir' in dspace.cfg "
                        + "is not a valid directory");
                System.exit(1);
            }
            File tempdir = new File(ziptempdir);
            if (!tempdir.exists() && !tempdir.mkdirs()) {
                log.error("Unable to create temporary directory");
            }
            sourcedir = ziptempdir + System.getProperty("file.separator") + line.getOptionValue("z");
            ziptempdir = ziptempdir + System.getProperty("file.separator") + line.getOptionValue("z")
                    + System.getProperty("file.separator");
        }

        ItemImport myloader = new ItemImport();

        // create a context
        Context c = new Context();

        // find the EPerson, assign to context
        EPerson myEPerson = null;

        if (eperson.indexOf('@') != -1) {
            // @ sign, must be an email
            myEPerson = EPerson.findByEmail(c, eperson);
        } else {
            myEPerson = EPerson.find(c, Integer.parseInt(eperson));
        }

        if (myEPerson == null) {
            System.out.println("Error, eperson cannot be found: " + eperson);
            System.exit(1);
        }

        c.setCurrentUser(myEPerson);

        // find collections
        Collection[] mycollections = null;

        // don't need to validate collections set if command is "delete"
        if (!"delete".equals(command)) {
            System.out.println("Destination collections:");

            mycollections = new Collection[collections.length];

            // validate each collection arg to see if it's a real collection
            for (int i = 0; i < collections.length; i++) {
                // is the ID a handle?
                if (collections[i].indexOf('/') != -1) {
                    // string has a / so it must be a handle - try and resolve
                    // it
                    mycollections[i] = (Collection) HandleManager.resolveToObject(c, collections[i]);

                    // resolved, now make sure it's a collection
                    if ((mycollections[i] == null) || (mycollections[i].getType() != Constants.COLLECTION)) {
                        mycollections[i] = null;
                    }
                }
                // not a handle, try and treat it as an integer collection
                // database ID
                else if (collections[i] != null) {
                    mycollections[i] = Collection.find(c, Integer.parseInt(collections[i]));
                }

                // was the collection valid?
                if (mycollections[i] == null) {
                    throw new IllegalArgumentException("Cannot resolve " + collections[i] + " to collection");
                }

                // print progress info
                String owningPrefix = "";

                if (i == 0) {
                    owningPrefix = "Owning ";
                }

                System.out.println(owningPrefix + " Collection: " + mycollections[i].getMetadata("name"));
            }
        } // end of validating collections

        try {
            // If this is a zip archive, unzip it first
            if (zip) {
                ZipFile zf = new ZipFile(zipfilename);
                ZipEntry entry;
                Enumeration<? extends ZipEntry> entries = zf.entries();
                while (entries.hasMoreElements()) {
                    entry = entries.nextElement();
                    if (entry.isDirectory()) {
                        if (!new File(ziptempdir + entry.getName()).mkdir()) {
                            log.error("Unable to create contents directory");
                        }
                    } else {
                        System.out.println("Extracting file: " + entry.getName());
                        int index = entry.getName().lastIndexOf('/');
                        if (index == -1) {
                            // Was it created on Windows instead?
                            index = entry.getName().lastIndexOf('\\');
                        }
                        if (index > 0) {
                            File dir = new File(ziptempdir + entry.getName().substring(0, index));
                            if (!dir.mkdirs()) {
                                log.error("Unable to create directory");
                            }
                        }
                        byte[] buffer = new byte[1024];
                        int len;
                        InputStream in = zf.getInputStream(entry);
                        BufferedOutputStream out = new BufferedOutputStream(
                                new FileOutputStream(ziptempdir + entry.getName()));
                        while ((len = in.read(buffer)) >= 0) {
                            out.write(buffer, 0, len);
                        }
                        in.close();
                        out.close();
                    }
                }
            }

            c.turnOffAuthorisationSystem();

            if ("add".equals(command)) {
                myloader.addItems(c, mycollections, sourcedir, mapfile, template);
            } else if ("replace".equals(command)) {
                myloader.replaceItems(c, mycollections, sourcedir, mapfile, template);
            } else if ("delete".equals(command)) {
                myloader.deleteItems(c, mapfile);
            } else if ("add-bte".equals(command)) {
                myloader.addBTEItems(c, mycollections, sourcedir, mapfile, template, bteInputType);
            }

            // complete all transactions
            c.complete();
        } catch (Exception e) {
            // abort all operations
            if (mapOut != null) {
                mapOut.close();
            }

            mapOut = null;

            c.abort();
            e.printStackTrace();
            System.out.println(e);
            status = 1;
        }

        // Delete the unzipped file
        try {
            if (zip) {
                System.gc();
                System.out.println("Deleting temporary zip directory: " + ziptempdir);
                ItemImport.deleteDirectory(new File(ziptempdir));
            }
        } catch (Exception ex) {
            System.out.println("Unable to delete temporary zip archive location: " + ziptempdir);
        }

        if (mapOut != null) {
            mapOut.close();
        }

        if (isTest) {
            System.out.println("***End of Test Run***");
        }
    } finally {
        DSIndexer.setBatchProcessingMode(false);
        Date endTime = new Date();
        System.out.println("Started: " + startTime.getTime());
        System.out.println("Ended: " + endTime.getTime());
        System.out.println("Elapsed time: " + ((endTime.getTime() - startTime.getTime()) / 1000) + " secs ("
                + (endTime.getTime() - startTime.getTime()) + " msecs)");
    }

    System.exit(status);
}

From source file:Main.java

public static Enumeration<?> getEntriesEnumeration(File zipFile) throws ZipException, IOException {
    ZipFile zf = new ZipFile(zipFile);
    return zf.entries();

}