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:org.eclipse.data.sampledb.SampledbActivator.java

/**
 * Initialization for first time startup in this instance of JVM
 *//*from   w  w  w.  j a va2s  .  co  m*/
private void init() throws IOException {
    assert dbDir == null;

    // Create and remember our private directory under system temp
    // Name it "BIRTSampleDB_$timestamp$_$classinstanceid$"
    String tempDir = System.getProperty("java.io.tmpdir");
    String timeStamp = String.valueOf(System.currentTimeMillis());
    String instanceId = Integer.toHexString(hashCode());
    dbDir = tempDir + "/BIRTSampleDB_" + timeStamp + "_" + instanceId;
    LOGGER.debug("Creating Sampledb database at location " + dbDir);
    (new File(dbDir)).mkdir();

    // Set up private copy of Sample DB in system temp directory

    // Get an input stream to read DB Jar file
    // handle getting db jar file on both OSGi and OSGi-less platforms
    String dbEntryName = SAMPLE_DB_HOME_DIR + FILE_DELIM + SAMPLE_DB_JAR_FILE;

    URL fileURL = SampledbActivator.class.getResource(dbEntryName);

    if (fileURL == null) {
        fileURL = this.getClass().getClassLoader().getResource(dbEntryName);
        if (fileURL == null) {
            String errMsg = "INTERNAL ERROR: SampleDB DB file not found: " + dbEntryName;
            LOGGER.error(errMsg);
            throw new RuntimeException(errMsg);
        }
    }

    // Copy entries in the DB jar file to corresponding location in db dir
    InputStream dbFileStream = new BufferedInputStream(fileURL.openStream());
    ZipInputStream zipStream = new ZipInputStream(dbFileStream);
    ZipEntry entry;
    while ((entry = zipStream.getNextEntry()) != null) {
        File entryFile = new File(dbDir, entry.getName());
        if (entry.isDirectory()) {
            entryFile.mkdir();
        } else {
            // Copy zip entry to local file
            OutputStream os = new FileOutputStream(entryFile);
            byte[] buf = new byte[4000];
            int len;
            while ((len = zipStream.read(buf)) > 0) {
                os.write(buf, 0, len);
            }
            os.close();
        }
    }

    zipStream.close();
    dbFileStream.close();
}

From source file:org.trianacode.taskgraph.tool.FileToolbox.java

/**
 * process a jar file/*from ww  w  .  j av a  2 s. c om*/
 *
 * @param url
 * @param streamable
 * @return
 * @throws Exception
 */
private List<Tool> processJar(URL url, Streamable streamable) throws Exception {
    List<Tool> ret = new ArrayList<Tool>();
    InputStream in = streamable.getInputStream();
    if (!(in instanceof ZipInputStream)) {
        in = new ZipInputStream(in);
    }
    ZipInputStream zin = (ZipInputStream) in;
    ZipEntry entry;
    while ((entry = zin.getNextEntry()) != null) {
        if (entry.getName().endsWith(EXT_TASKGRAPH)) {
            byte[] buff = new byte[2048];
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            int c;
            while ((c = zin.read(buff)) != -1) {
                bout.write(buff, 0, c);
            }
            ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
            List<Tool> xmls = processXml(new StreamableStream(bin));
            ret.addAll(xmls);
        } else if (entry.getName().endsWith(EXT_JAVA_CLASS)) {
            List<Tool> clss = processClass(new URL("jar:" + url.toString() + "!/" + entry.getName()));
            ret.addAll(clss);
        }
    }
    return ret;
}

From source file:com.sastix.cms.server.services.content.impl.ZipFileHandlerServiceImpl.java

@Override
public DataMaps unzip(byte[] bytes) throws IOException {
    Map<String, String> foldersMap = new HashMap<>();

    Map<String, byte[]> extractedBytesMap = new HashMap<>();
    InputStream byteInputStream = new ByteArrayInputStream(bytes);
    //validate that it is a zip file
    if (isZipFile(bytes)) {
        try {//  w w w .j a  v a 2s  .  c o m
            //get the zip file content
            ZipInputStream zis = new ZipInputStream(byteInputStream);
            //get the zipped file list entry
            ZipEntry ze = zis.getNextEntry();

            while (ze != null) {
                String fileName = ze.getName();
                if (!ze.isDirectory()) {//if entry is a directory, we should not add it as a file
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    try {
                        ByteBuffer bufIn = ByteBuffer.allocate(1024);
                        int bytesRead;
                        while ((bytesRead = zis.read(bufIn.array())) > 0) {
                            baos.write(bufIn.array(), 0, bytesRead);
                            bufIn.rewind();
                        }
                        bufIn.clear();
                        extractedBytesMap.put(fileName, baos.toByteArray());
                    } finally {
                        baos.close();
                    }
                } else {
                    foldersMap.put(fileName, fileName);
                }
                ze = zis.getNextEntry();
            }
            zis.closeEntry();
            zis.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    DataMaps dataMaps = new DataMaps();
    dataMaps.setBytesMap(extractedBytesMap);
    dataMaps.setFoldersMap(foldersMap);
    return dataMaps;
}

From source file:com.wakatime.eclipse.plugin.Dependencies.java

private void unzip(String zipFile, File outputDir) throws IOException {
    if (!outputDir.exists())
        outputDir.mkdirs();/*  w w  w. j a  va 2 s .  c o  m*/

    byte[] buffer = new byte[1024];
    ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
    ZipEntry ze = zis.getNextEntry();

    while (ze != null) {
        String fileName = ze.getName();
        File newFile = new File(outputDir, fileName);

        if (ze.isDirectory()) {
            // WakaTime.log("Creating directory: "+newFile.getParentFile().getAbsolutePath());
            newFile.mkdirs();
        } else {
            // WakaTime.log("Extracting File: "+newFile.getAbsolutePath());
            FileOutputStream fos = new FileOutputStream(newFile.getAbsolutePath());
            int len;
            while ((len = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            fos.close();
        }

        ze = zis.getNextEntry();
    }

    zis.closeEntry();
    zis.close();
}

From source file:org.apache.stratos.python.cartridge.agent.integration.tests.PythonAgentIntegrationTest.java

private void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
    byte[] bytesIn = new byte[4096];
    int read = 0;
    while ((read = zipIn.read(bytesIn)) != -1) {
        bos.write(bytesIn, 0, read);/*from  ww w  . ja  v  a 2 s .com*/
    }
    bos.close();
}

From source file:com.alcatel_lucent.nz.wnmsextract.reader.FileSelector.java

protected File unzip3(File zf) throws FileNotFoundException {
    //File f = null;
    String rename = zf.getAbsolutePath().replaceFirst("\\.zip", identifier + ".xml");//.replaceFirst("\\.gz", ".xml");
    File f = new File(rename);
    try {//  www.j  av a  2  s. co  m
        FileInputStream fis = new FileInputStream(zf);

        ZipInputStream zin = new ZipInputStream(fis);
        ZipEntry ze;

        final byte[] content = new byte[BUFFER];

        while ((ze = zin.getNextEntry()) != null) {
            f = new File(getCalTempPath() + File.separator + ze.getName());
            FileOutputStream fos = new FileOutputStream(f);
            BufferedOutputStream bos = new BufferedOutputStream(fos, content.length);

            int n = 0;
            while (-1 != (n = zin.read(content))) {
                bos.write(content, 0, n);
            }
            bos.flush();
            bos.close();
        }

        fis.close();
        zin.close();
    } catch (IOException ioe) {
        jlog.error("Error processing Zip " + zf + " Excluding! :: " + ioe);
        return null;
    }
    //try again... what could go wrong
    /*
    if (checkMinFileSize(f) && retry_counter<MAX_UNGZIP_RETRIES){
       retry_counter++;
       f.delete();
       f = unzip2(zf);
    }
    */
    return f;
}

From source file:org.photovault.imginfo.DataExporter.java

/**
 * Reads a zip file entry into byte array
 * @param e The entry to read/* w w  w.j a  va 2 s .  c o  m*/
 * @param zipis ZipInputStream that is read
 * @return The data in entry
 * @throws IOException
 */

private byte[] readZipEntry(ZipEntry e, ZipInputStream zipis) throws IOException {
    long esize = e.getSize();
    byte[] data = null;
    if (esize > 0) {
        data = new byte[(int) esize];
        zipis.read(data);
    } else {
        byte[] tmp = new byte[65536];
        int offset = 0;
        int bytesRead = 0;
        while ((bytesRead = zipis.read(tmp, offset, tmp.length - offset)) > 0) {
            offset += bytesRead;
            if (offset >= tmp.length) {
                tmp = Arrays.copyOf(tmp, tmp.length * 2);
            }
        }
        data = Arrays.copyOf(tmp, offset);
    }
    return data;
}

From source file:org.geoserver.wfs.response.ShapeZipTest.java

private String getCharset(final InputStream in) throws IOException {
    ZipInputStream zis = new ZipInputStream(in);
    ZipEntry entry = null;//from  w w  w  .  ja v a  2 s . c  o  m
    byte[] bytes = new byte[1024];
    while ((entry = zis.getNextEntry()) != null) {
        if (entry.getName().endsWith(".cst")) {
            zis.read(bytes);
        }
    }
    zis.close();

    if (bytes == null)
        return null;
    else
        return new String(bytes).trim();
}

From source file:org.geoserver.wfs.response.ShapeZipTest.java

private String getRequest(final InputStream in) throws IOException {
    ZipInputStream zis = new ZipInputStream(in);
    ZipEntry entry = null;/*  w ww.  j  av  a 2  s . c om*/
    byte[] bytes = new byte[1024];
    while ((entry = zis.getNextEntry()) != null) {
        if (entry.getName().endsWith(".txt")) {
            zis.read(bytes);
        }
    }
    zis.close();

    if (bytes == null)
        return null;
    else
        return new String(bytes).trim();
}

From source file:org.adl.samplerte.server.LMSPackageHandler.java

/****************************************************************************
**
** Method:   extract()/*from  w ww  .  j a  v a 2 s . c  o  m*/
** Input:  String zipFileName  --  The name of the zip file to be used
**         Sting  extractedFile  --  The name of the file to be extracted 
**                                   from the zip    
** Output:   none
**
** Description: This method takes in the name of a zip file and a file to
**              be extracted from the zip format.  The method locates the
**              file and extracts into the '.' directory.
**              
*****************************************************************************/
public static String extract(String zipFileName, String extractedFile, String pathOfExtract) {
    if (_Debug) {
        System.out.println("***********************");
        System.out.println("in extract()           ");
        System.out.println("***********************");
        System.out.println("zip file: " + zipFileName);
        System.out.println("file to extract: " + extractedFile);
    }

    String nameOfExtractedFile = new String("");
    System.out.println("-----LMSPackageHandler-extract()----");
    System.out.println("zipFileName=" + zipFileName);
    System.out.println("extractedFile=" + extractedFile);
    System.out.println("pathOfExtract=" + pathOfExtract);
    try {
        String pathAndName = new String("");
        int index = zipFileName.lastIndexOf("\\") + 1;
        zipFileName = zipFileName.substring(index);
        System.out.println("---zipFileName=" + zipFileName);
        //  Input stream for the zip file (package)
        ZipInputStream in = new ZipInputStream(new FileInputStream(pathOfExtract + "\\" + zipFileName));

        //  Cut the path off of the name of the file. (for writing the file)
        int indexOfFileBeginning = extractedFile.lastIndexOf("/") + 1;
        System.out.println("---indexOfFileBeginning=" + indexOfFileBeginning);
        nameOfExtractedFile = extractedFile.substring(indexOfFileBeginning);
        System.out.println("---nameOfExtractedFile=" + nameOfExtractedFile);
        pathAndName = pathOfExtract + "\\" + nameOfExtractedFile;
        System.out.println("pathAndName=" + pathAndName);
        //  Ouput stream for the extracted file
        //*************************************
        //*************************************
        OutputStream out = new FileOutputStream(pathAndName);
        //OutputStream out = new FileOutputStream(nameOfExtractedFile);

        ZipEntry entry;
        byte[] buf = new byte[1024];
        int len;
        int flag = 0;

        while (flag != 1) {
            entry = in.getNextEntry();

            if ((entry.getName()).equalsIgnoreCase(extractedFile)) {
                if (_Debug) {
                    System.out.println("Found file to extract...  extracting to " + pathOfExtract);
                }
                flag = 1;
            }
        }

        while ((len = in.read(buf)) > 0) {

            out.write(buf, 0, len);
        }

        out.close();
        in.close();
    } catch (IOException e) {
        if (_Debug) {
            System.out.println("IO Exception Caught: " + e);
        }
        e.printStackTrace();
    }
    return nameOfExtractedFile;
}