Example usage for java.util.zip ZipInputStream read

List of usage examples for java.util.zip ZipInputStream read

Introduction

In this page you can find the example usage for java.util.zip ZipInputStream read.

Prototype

public int read(byte b[]) throws IOException 

Source Link

Document

Reads up to b.length bytes of data from this input stream into an array of bytes.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    ZipInputStream in = new ZipInputStream(new FileInputStream("source.zip"));
    OutputStream out = new FileOutputStream("target");
    byte[] buf = new byte[1024];
    int len;/*w w  w. j  ava 2  s .c  om*/
    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    out.close();
    in.close();
}

From source file:Main.java

  public static void main(String[] argv) throws Exception {
  String inFilename = "infile.zip";
  ZipInputStream in = new ZipInputStream(new FileInputStream(inFilename));

  ZipEntry entry = in.getNextEntry();

  String outFilename = "o";
  OutputStream out = new FileOutputStream(outFilename);

  byte[] buf = new byte[1024];
  int len;//ww  w  .j  a  v a2 s  .com
  while ((len = in.read(buf)) > 0) {
    out.write(buf, 0, len);
  }

  out.close();
  in.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    ZipInputStream inStream = new ZipInputStream(new FileInputStream("compressed.zip"));
    OutputStream outStream = new FileOutputStream("extracted.txt");

    byte[] buffer = new byte[1024];
    int read;//from   w w w  . j  a v a 2s . c  o  m
    ZipEntry entry;
    if ((entry = inStream.getNextEntry()) != null) {
        while ((read = inStream.read(buffer)) > 0) {
            outStream.write(buffer, 0, read);
        }
    }
    outStream.close();
    inStream.close();
}

From source file:org.springframework.data.keyvalue.riak.util.RiakClassFileLoader.java

public static void main(String[] args) {
    Parser p = new BasicParser();
    CommandLine cl = null;/*  w ww .j  a va2s  .c o m*/
    try {
        cl = p.parse(opts, args);
    } catch (ParseException e) {
        System.err.println("Error parsing command line: " + e.getMessage());
    }

    if (null != cl) {
        boolean verbose = cl.hasOption('v');
        RiakTemplate riak = new RiakTemplate();
        riak.getRestTemplate().setErrorHandler(new Ignore404sErrorHandler());
        if (cl.hasOption('u')) {
            riak.setDefaultUri(cl.getOptionValue('u'));
        }
        try {
            riak.afterPropertiesSet();
        } catch (Exception e) {
            System.err.println("Error creating RiakTemplate: " + e.getMessage());
        }
        String[] files = cl.getOptionValues('j');
        if (null != files) {
            for (String file : files) {
                if (verbose) {
                    System.out.println(String.format("Loading JAR file %s into Riak...", file));
                }
                try {
                    File zfile = new File(file);
                    ZipInputStream zin = new ZipInputStream(new FileInputStream(zfile));
                    ZipEntry entry;
                    while (null != (entry = zin.getNextEntry())) {
                        ByteArrayOutputStream bout = new ByteArrayOutputStream();
                        byte[] buff = new byte[16384];
                        for (int bytesRead = zin.read(buff); bytesRead > 0; bytesRead = zin.read(buff)) {
                            bout.write(buff, 0, bytesRead);
                        }

                        if (entry.getName().endsWith(".class")) {
                            String name = entry.getName().replaceAll("/", ".");
                            name = URLEncoder.encode(name.substring(0, name.length() - 6), "UTF-8");
                            String bucket;
                            if (cl.hasOption('b')) {
                                bucket = cl.getOptionValue('b');
                            } else {
                                bucket = URLEncoder.encode(zfile.getCanonicalFile().getName(), "UTF-8");
                            }
                            if (verbose) {
                                System.out.println(String.format("Uploading to %s/%s", bucket, name));
                            }

                            // Load these bytes into Riak
                            riak.setAsBytes(bucket, name, bout.toByteArray());
                        }
                    }
                } catch (FileNotFoundException e) {
                    System.err.println("Error reading JAR file: " + e.getMessage());
                } catch (IOException e) {
                    System.err.println("Error reading JAR file: " + e.getMessage());
                }
            }
        }

        String[] classFiles = cl.getOptionValues('c');
        if (null != classFiles) {
            for (String classFile : classFiles) {
                try {
                    FileInputStream fin = new FileInputStream(classFile);
                    ByteArrayOutputStream bout = new ByteArrayOutputStream();
                    byte[] buff = new byte[16384];
                    for (int bytesRead = fin.read(buff); bytesRead > 0; bytesRead = fin.read(buff)) {
                        bout.write(buff, 0, bytesRead);
                    }

                    String name;
                    if (cl.hasOption('k')) {
                        name = cl.getOptionValue('k');
                    } else {
                        throw new IllegalStateException(
                                "Must specify a Riak key in which to store the data if loading individual class files.");
                    }
                    String bucket;
                    if (cl.hasOption('b')) {
                        bucket = cl.getOptionValue('b');
                    } else {
                        throw new IllegalStateException(
                                "Must specify a Riak bucket in which to store the data if loading individual class files.");
                    }
                    if (verbose) {
                        System.out.println(String.format("Uploading to %s/%s", bucket, name));
                    }

                    // Load these bytes into Riak
                    riak.setAsBytes(bucket, name, bout.toByteArray());

                } catch (FileNotFoundException e) {
                    System.err.println("Error reading class file: " + e.getMessage());
                } catch (IOException e) {
                    System.err.println("Error reading class file: " + e.getMessage());
                }
            }
        }
    }
}

From source file:org.hecl.androidbuilder.AndroidBuilder.java

public static void main(String[] args) throws IOException, ParseException {
    String androiddir = null;//from   w  w  w. j a va2 s  .  c  o  m

    Options opts = new Options();

    /* Define some command line options. */
    opts.addOption("android", true, "android SDK location");
    opts.addOption("class", true, "New class name");
    opts.addOption("package", true, "New package name, like bee.bop.foo.bar");
    opts.addOption("label", true, "Label");
    opts.addOption("permissions", true, "Android Permissions");
    opts.addOption("intentfilter", true, "Intent Filter File");
    opts.addOption("extraclass", true, "Extra class");
    opts.addOption("script", true, "Script file");

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(opts, args);

    /* Get the android directory, or fail if it's not given. */
    if (cmd.hasOption("android")) {
        androiddir = cmd.getOptionValue("android");
    } else {
        usage(opts);
    }
    String aapt = androiddir + sep + "tools" + sep + "aapt";
    String dx = androiddir + sep + "tools" + sep + "dx";
    if (sep == "\\") {
        /* It's windows  */
        dx += ".bat";
    }

    String androidjar = androiddir + sep + "android.jar";

    /* Get the application's class name.  */
    String appclass = "Hackle";
    if (cmd.hasOption("class")) {
        appclass = cmd.getOptionValue("class");
    }

    /* Get the application's label. */
    String appname = "Hecl Hackle";
    if (cmd.hasOption("label")) {
        appname = cmd.getOptionValue("label");
    }

    /* Get the fake package name. */
    String packagename = "bee.bop.doo.wah";
    if (cmd.hasOption("package")) {
        packagename = cmd.getOptionValue("package");
    }

    String perms = "";
    if (cmd.hasOption("permissions")) {
        for (String p : cmd.getOptionValue("permissions").split(",")) {
            perms += "<uses-permission android:name=\"android.permission." + p + "\" />\n";
        }
    }

    boolean hasextraClass = false;
    String extraClass = "";
    if (cmd.hasOption("extraclass")) {
        hasextraClass = true;
        extraClass = cmd.getOptionValue("extraclass");
    }

    String intentfilterFile = "";
    if (cmd.hasOption("intentfilter")) {
        intentfilterFile = cmd.getOptionValue("intentfilter");
    }

    String scriptFilename = null;
    if (cmd.hasOption("script")) {
        scriptFilename = cmd.getOptionValue("script");
    }

    /* Calculate some other stuff based on the informatin we have. */
    String tmpdir = System.getProperty("java.io.tmpdir");
    File dirnamefile = new File(tmpdir, appclass + "-" + System.currentTimeMillis());
    String dirname = dirnamefile.toString();
    String manifest = dirname + sep + "AndroidManifest.xml";
    String tmppackage = dirname + sep + "Temp.apk";
    String hecljar = dirname + sep + "Hecl.jar";
    String heclapk = dirname + sep + "Hecl.apk";
    String resdir = dirname + sep + "res";
    String icondir = resdir + sep + "drawable";
    String iconfile = (new File(icondir, "aicon.png")).toString();

    String intentreceiver = "";
    /* If we have an intent filter .xml file, read it and add its
     * contents. */
    if (!intentfilterFile.equals("")) {
        StringBuffer sb = new StringBuffer("");
        FileInputStream fis = new FileInputStream(intentfilterFile);
        int c = 0;
        while ((c = fis.read()) != -1) {
            sb.append((char) c);
        }
        fis.close();
        intentreceiver = sb.toString();
    }

    /* The AndroidManifest.xml template. */
    String xmltemplate = "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" \n"
            + "package=\"" + packagename + "\">\n" + perms + "<application android:icon=\"@drawable/aicon\">\n"
            +
            /* Main activity */
            "<activity android:name=\"" + appclass + "\" android:label=\"" + appname + "\">\n"
            + "<intent-filter>\n" + "<action android:name=\"android.intent.action.MAIN\" />\n"
            + "<category android:name=\"android.intent.category.LAUNCHER\" />\n" + "</intent-filter>\n"
            + "</activity>\n" +
            /* SubHecl */
            "<activity android:name=\"" + "Sub" + appclass + "\" android:label=\"SubHecl\">\n"
            + "<intent-filter>\n" + "<action android:name=\"android.intent.action.MAIN\" />\n"
            + "</intent-filter>\n" + "</activity>\n" +

            /* Intent Receiver. */

            intentreceiver +

            "</application>\n" + "</manifest>\n";

    /* Template for the main .java file. */
    String mainClassTemplate = "package " + packagename + ";\n" + "import org.hecl.android.Hecl;\n"
            + "import org.hecl.HeclException;\n" + "import org.hecl.Interp;\n"
            + "import org.hecl.java.JavaCmd;\n" + "public class " + appclass + " extends Hecl {\n"
            + "protected void createCommands(Interp i) throws HeclException {\n" + "JavaCmd.load(interp, \""
            + packagename + "." + appclass + "\", \"hecl\");\n" + "JavaCmd.load(interp, \"" + packagename
            + ".Sub" + appclass + "\", \"subhecl\");\n" + "}\n" + "}\n";

    /* Template for the sub file. */
    String subClassTemplate = "package " + packagename + ";\n" + "import org.hecl.android.SubHecl;\n"
            + "public class Sub" + appclass + " extends SubHecl {}\n";

    /* First we write out the AndroidManifest.xml file.  */
    (new File(dirname)).mkdir();
    FileWriter outputstream = null;
    try {
        outputstream = new FileWriter(manifest);
        outputstream.write(xmltemplate);
    } catch (IOException e) {
        System.err.println("Couldn't write to " + manifest + " : " + e.toString());
        System.exit(1);
    } finally {
        if (outputstream != null) {
            outputstream.close();
        }
    }

    InputStream is = null;
    FileOutputStream fos = null;

    /* Make a directory for the icon. */
    (new File(icondir)).mkdirs();

    copyFileStream(AndroidBuilder.class.getResourceAsStream("/android/res/drawable/aicon.png"),
            new FileOutputStream(iconfile));

    /* Now, we run aapt to generate a new, compressed .xml file... */
    runProcess(aapt, "package", "-f", "-M", manifest, "-S", resdir, "-I", androidjar, "-F", tmppackage);

    /* Then we extract it, overwriting AndroidManifest.xml*/
    ZipFile zipfile = new ZipFile(tmppackage);
    ZipEntry newmanifest = zipfile.getEntry("AndroidManifest.xml");
    System.out.println("newmanifest is " + newmanifest);
    is = zipfile.getInputStream(newmanifest);
    fos = new FileOutputStream(manifest);
    copyFileStream(is, fos);

    /* Now, we copy in Hecl.jar  ...  */
    is = AndroidBuilder.class.getResourceAsStream("/android/Hecl.jar");
    fos = new FileOutputStream(hecljar);
    copyFileStream(is, fos);

    /* ... and the Hecl.apk. */
    is = AndroidBuilder.class.getResourceAsStream("/android/bin/Hecl.apk");
    fos = new FileOutputStream(heclapk);
    copyFileStream(is, fos);

    /* Now, we can create some Java classes ...  */
    String packagedir = dirname;
    String jarpackagedir = ""; /* The name inside the jar file. */
    for (String s : packagename.split("\\.")) {
        packagedir += sep + s;
        jarpackagedir += s + sep;
    }
    (new File(packagedir)).mkdirs();

    String mainJava = packagedir + sep + appclass + ".java";
    String subJava = packagedir + sep + "Sub" + appclass + ".java";
    String mainClass = jarpackagedir + appclass + ".class";
    String subClass = jarpackagedir + "Sub" + appclass + ".class";

    /* Output a new 'main' class. */
    fos = new FileOutputStream(mainJava);
    fos.write(mainClassTemplate.getBytes());
    fos.close();

    /* Output a new 'sub' class. */
    fos = new FileOutputStream(subJava);
    fos.write(subClassTemplate.getBytes());
    fos.close();

    /* Compile the new classes. */
    runProcess("javac", mainJava, subJava, "-cp", hecljar + pathsep + androidjar);

    /* Stash them in the .jar. */
    runProcess("jar", "uf", hecljar, "-C", dirname, mainClass);
    runProcess("jar", "uf", hecljar, "-C", dirname, subClass);

    /* If there is an extra class, move it into the .jar */
    if (hasextraClass) {
        File ec = new File(extraClass);
        is = new FileInputStream(ec);
        String outfile = dirname + sep + jarpackagedir + ec.getName();
        System.out.println("Moving " + extraClass + " to " + outfile);
        fos = new FileOutputStream(outfile);
        copyFileStream(is, fos);
        runProcess("jar", "uf", hecljar, "-C", dirname, jarpackagedir + ec.getName());
    }

    /* Run the dx program to turn them into Android dex stuff. */
    String dexfile = dirname + sep + "classes.dex";
    runProcess(dx, "-JXmx384M", "--dex", "--output=" + dexfile, "--positions=lines", hecljar);

    /* Finally, rename the whole business back to the calling
     * directory.  We copy the whole thing across as a .zip
     * archive in order to replace the script.hcl file. */

    String newfilename = System.getProperty("user.dir") + sep + appclass + ".apk";
    if (scriptFilename == null) {
        /* Just move it over. */
        (new File(heclapk)).renameTo(new File(newfilename));
    } else {
        /* Copy it bit by bit, and replace the script.hcl file. */
        ZipInputStream zif = new ZipInputStream(new FileInputStream(heclapk));
        ZipOutputStream zof = new ZipOutputStream(new FileOutputStream(newfilename));

        int read;
        byte[] buf = new byte[4096];
        ZipEntry ze = zif.getNextEntry();
        while (ze != null) {
            zof.putNextEntry(new ZipEntry(ze.getName()));
            if ("res/raw/script.hcl".equals(ze.getName())) {
                FileInputStream inf = new FileInputStream(scriptFilename);
                while ((read = inf.read(buf)) != -1) {
                    zof.write(buf, 0, read);
                }
                inf.close();
                /* Replace the apk's AndroidManifest.xml ... */
            } else if ("AndroidManifest.xml".equals(ze.getName())) {
                FileInputStream inf = new FileInputStream(manifest);
                while ((read = inf.read(buf)) != -1) {
                    zof.write(buf, 0, read);
                }
                inf.close();
                /* ... and classes.dex  */
            } else if ("classes.dex".equals(ze.getName())) {
                FileInputStream inf = new FileInputStream(dexfile);
                while ((read = inf.read(buf)) != -1) {
                    zof.write(buf, 0, read);
                }
                inf.close();
            } else {
                while ((read = zif.read(buf)) != -1) {
                    zof.write(buf, 0, read);
                }
            }
            ze = zif.getNextEntry();
        }

        zif.close();
        zof.close();
    }

    /* FIXME - we should probably destroy the temporary directory,
     * but it's very useful for debugging purposes.  */
}

From source file:org.apache.batchee.cli.zip.Zips.java

private static void copy(final ZipInputStream from, final OutputStream to) throws IOException {
    final byte[] buffer = new byte[COPY_BUFFER_SIZE];
    int length;//from w w w  .j  a va2  s  .  com
    while ((length = from.read(buffer)) != -1) {
        to.write(buffer, 0, length);
    }
    to.flush();
}

From source file:Main.java

protected static File unzipEntry(ZipInputStream zis, File targetFile) throws Exception {
    FileOutputStream fos = null;//from www  .  ja v a 2 s .  co  m
    try {
        fos = new FileOutputStream(targetFile);

        byte[] buffer = new byte[BUFFER_SIZE];
        int len = 0;
        while ((len = zis.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
        }
    } finally {
        if (fos != null) {
            fos.close();
        }
    }
    return targetFile;
}

From source file:Main.java

public static void extractFile(ZipInputStream in, File outdir, String name) throws IOException {
    byte[] buffer = new byte[BUFFER_SIZE];
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(outdir, name)));
    int count = -1;
    while ((count = in.read(buffer)) != -1)
        out.write(buffer, 0, count);// w  w  w . j a  va2s. c  om
    out.close();
}

From source file:org.exist.util.Compressor.java

public static void uncompress(byte[] whatToUncompress, OutputStream os) throws IOException {
    final ByteArrayInputStream bais = new ByteArrayInputStream(whatToUncompress);
    final ZipInputStream gzis = new ZipInputStream(bais);
    final ZipEntry zipentry = gzis.getNextEntry();
    Integer.parseInt(zipentry.getName());
    final byte[] buf = new byte[512];
    int bread;//from   w  ww .j  a v  a2s  . co  m
    while ((bread = gzis.read(buf)) != -1)
        os.write(buf, 0, bread);
    gzis.closeEntry();
    gzis.close();
}

From source file:com.microsoft.azure.hdinsight.util.HDInsightJobViewUtils.java

private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
    BufferedOutputStream bos = new BufferedOutputStream(new java.io.FileOutputStream(filePath));
    byte[] bytesIn = new byte[BUFFER_SIZE];
    int read = 0;
    while ((read = zipIn.read(bytesIn)) != -1) {
        bos.write(bytesIn, 0, read);/*from   www.j  a va 2  s.  co  m*/
    }
    bos.close();
}