Example usage for java.util.zip ZipEntry isDirectory

List of usage examples for java.util.zip ZipEntry isDirectory

Introduction

In this page you can find the example usage for java.util.zip ZipEntry isDirectory.

Prototype

public boolean isDirectory() 

Source Link

Document

Returns true if this is a directory entry.

Usage

From source file:org.apache.nutch.parse.zip.ZipTextExtractor.java

public String extractText(InputStream input, String url, List outLinksList) throws IOException {
    String resultText = "";
    byte temp;/*from   w  w w .  jav a 2s . c o m*/

    ZipInputStream zin = new ZipInputStream(input);

    ZipEntry entry;

    while ((entry = zin.getNextEntry()) != null) {

        if (!entry.isDirectory()) {
            int size = (int) entry.getSize();
            byte[] b = new byte[size];
            for (int x = 0; x < size; x++) {
                int err = zin.read();
                if (err != -1) {
                    b[x] = (byte) err;
                }
            }
            String newurl = url + "/";
            String fname = entry.getName();
            newurl += fname;
            URL aURL = new URL(newurl);
            String base = aURL.toString();
            int i = fname.lastIndexOf('.');
            if (i != -1) {
                // Trying to resolve the Mime-Type
                String contentType = MIME.getMimeType(fname).getName();
                try {
                    Metadata metadata = new Metadata();
                    metadata.set(Response.CONTENT_LENGTH, Long.toString(entry.getSize()));
                    metadata.set(Response.CONTENT_TYPE, contentType);
                    Content content = new Content(newurl, base, b, contentType, metadata, this.conf);
                    Parse parse = new ParseUtil(this.conf).parse(content).get(content.getUrl());
                    ParseData theParseData = parse.getData();
                    Outlink[] theOutlinks = theParseData.getOutlinks();

                    for (int count = 0; count < theOutlinks.length; count++) {
                        outLinksList.add(
                                new Outlink(theOutlinks[count].getToUrl(), theOutlinks[count].getAnchor()));
                    }

                    resultText += entry.getName() + " " + parse.getText() + " ";
                } catch (ParseException e) {
                    if (LOG.isInfoEnabled()) {
                        LOG.info("fetch okay, but can't parse " + fname + ", reason: " + e.getMessage());
                    }
                }
            }
        }
    }

    return resultText;
}

From source file:de.lazyzero.kkMulticopterFlashTool.utils.Zip.java

public static void unzip2folder(File zipFile, File toFolder) throws FileExistsException {
    if (!toFolder.exists()) {
        toFolder.mkdirs();/* w  w w  .jav  a2s  . c o  m*/
    } else if (toFolder.isFile()) {
        throw new FileExistsException(toFolder.getName());
    }

    try {
        ZipEntry entry;
        @SuppressWarnings("resource")
        ZipFile zipfile = new ZipFile(zipFile);
        Enumeration<? extends ZipEntry> e = zipfile.entries();
        while (e.hasMoreElements()) {
            entry = e.nextElement();

            //            String newDir;
            //            if (entry.getName().indexOf("/") == -1) {
            //               newDir = zipFile.getName().substring(0, zipFile.getName().indexOf("."));
            //            } else {
            //               newDir = entry.getName().substring(0, entry.getName().indexOf("/"));
            //            }
            //            String folder = toFolder + (File.separatorChar+"") + newDir;
            //            System.out.println(folder);
            //            if ((new File(folder).mkdir())) {
            //               System.out.println("Done.");
            //            }
            System.out.println("Extracting: " + entry);
            if (entry.isDirectory()) {
                new File(toFolder + (File.separatorChar + "") + entry.getName()).mkdir();
            } else {
                BufferedInputStream is = new BufferedInputStream(zipfile.getInputStream(entry));
                int count;
                byte data[] = new byte[2048];
                String fileName = toFolder + (File.separatorChar + "") + entry.getName();
                FileOutputStream fos = new FileOutputStream(fileName);
                BufferedOutputStream dest = new BufferedOutputStream(fos, 2048);
                while ((count = is.read(data, 0, 2048)) != -1) {
                    dest.write(data, 0, count);
                }
                dest.flush();
                dest.close();
                is.close();
                System.out.println("extracted to: " + fileName);
            }

        }
    } catch (ZipException e1) {
        zipFile.delete();
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } finally {

    }

}

From source file:de.fhg.iais.cortex.services.ingest.ZipStreamAipBinaries.java

public INamedBinaryStream takeBinary() throws IOException {
    ZipEntry zipEntry;
    do {/*  ww  w  . ja v  a  2s. c o m*/
        zipEntry = this.zipInputStream.getNextEntry();

        if (zipEntry == null) {
            return null;
        }
    } while (zipEntry.isDirectory());

    InputStream stream = new CloseShieldInputStream(this.zipInputStream);
    return new NamedBinaryStream(zipEntry.getName(), stream);
}

From source file:org.apache.sling.jcr.contentloader.internal.readers.ZipReader.java

/**
 * @see org.apache.sling.jcr.contentloader.ContentReader#parse(java.io.InputStream, org.apache.sling.jcr.contentloader.ContentCreator)
 *//*from  w  ww .j  a va 2 s.c o m*/
public void parse(InputStream ins, ContentCreator creator) throws IOException, RepositoryException {
    try {
        creator.createNode(null, NT_FOLDER, null);
        final ZipInputStream zis = new ZipInputStream(ins);
        ZipEntry entry;
        do {
            entry = zis.getNextEntry();
            if (entry != null) {
                if (!entry.isDirectory()) {
                    String name = entry.getName();
                    int pos = name.lastIndexOf('/');
                    if (pos != -1) {
                        creator.switchCurrentNode(name.substring(0, pos), NT_FOLDER);
                    }
                    creator.createFileAndResourceNode(name, new CloseShieldInputStream(zis), null,
                            entry.getTime());
                    creator.finishNode();
                    creator.finishNode();
                    if (pos != -1) {
                        creator.finishNode();
                    }
                }
                zis.closeEntry();
            }

        } while (entry != null);
        creator.finishNode();
    } finally {
        if (ins != null) {
            try {
                ins.close();
            } catch (IOException ignore) {
            }
        }
    }
}

From source file:com.opengamma.integration.copier.portfolio.reader.ZippedPortfolioReader.java

private PortfolioReader getReader(ZipEntry entry) {

    if (!entry.isDirectory()
            && entry.getName().substring(entry.getName().lastIndexOf('.')).equalsIgnoreCase(SHEET_EXTENSION)) {
        try {//ww w. ja  v a  2 s. com
            // Extract full path
            String[] fullPath = entry.getName().split("/");

            // Extract security name
            String secType = fullPath[fullPath.length - 1].substring(0,
                    fullPath[fullPath.length - 1].lastIndexOf('.'));

            _currentPath = (String[]) ArrayUtils.subarray(fullPath, 0, fullPath.length - 1);

            // Set up a sheet reader and a row parser for the current CSV file in the ZIP archive
            SheetReader sheet = new CsvSheetReader(_zipFile.getInputStream(entry));

            RowParser parser = JodaBeanRowParser.newJodaBeanRowParser(secType);
            if (parser == null) {
                s_logger.error("Could not build a row parser for security type '" + secType + "'");
                return null;
            }
            if (!_ignoreVersion) {
                if (_versionMap.get(secType) == null) {
                    s_logger.error("Versioning hash for security type '" + secType + "' could not be found");
                    return null;
                }
                if (parser.getSecurityHashCode() != _versionMap.get(secType)) {
                    s_logger.error("The parser version for the '" + secType + "' security (hash "
                            + Integer.toHexString(parser.getSecurityHashCode())
                            + ") does not match the data stored in the archive (hash "
                            + Integer.toHexString(_versionMap.get(secType)) + ")");
                    return null;
                }
            }

            s_logger.info("Processing rows in archive entry " + entry.getName() + " as " + secType);

            // Create a simple portfolio reader for the current sheet
            return new SingleSheetSimplePortfolioReader(sheet, parser);

        } catch (Throwable ex) {
            s_logger.warn(
                    "Could not import from " + entry.getName() + ", skipping file (exception is " + ex + ")");
            return null;
        }
    } else {
        return null;
    }
}

From source file:UnpackedJarFile.java

public static void unzipToDirectory(ZipFile zipFile, File destDir) throws IOException {
    Enumeration entries = zipFile.entries();
    try {/*from   w ww.  j  av  a 2s  .c om*/
        while (entries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            if (entry.isDirectory()) {
                File dir = new File(destDir, entry.getName());
                createDirectory(dir);
            } else {
                File file = new File(destDir, entry.getName());
                createDirectory(file.getParentFile());
                OutputStream out = null;
                InputStream in = null;
                try {
                    out = new BufferedOutputStream(new FileOutputStream(file));
                    in = zipFile.getInputStream(entry);
                    writeAll(in, out);
                } finally {
                    if (null != out) {
                        out.close();
                    }
                    if (null != in) {
                        in.close();
                    }
                }
            }
        }
    } finally {
        zipFile.close();
    }
}

From source file:de.onyxbits.raccoon.ptools.ToolSupport.java

private void unzip(File file) throws IOException {
    ZipFile zipFile = new ZipFile(file);
    try {/*www  .ja  v  a2  s  .  co m*/
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            File entryDestination = new File(binDir, entry.getName());
            if (entry.isDirectory())
                entryDestination.mkdirs();
            else {
                entryDestination.getParentFile().mkdirs();
                InputStream in = zipFile.getInputStream(entry);
                OutputStream out = new FileOutputStream(entryDestination);
                IOUtils.copy(in, out);
                IOUtils.closeQuietly(in);
                out.close();
            }
        }
    } finally {
        zipFile.close();
    }
}

From source file:com.s2g.pst.resume.importer.UnZipHelper.java

/**
 * Unzip it//from ww w.j  a v a  2s. c  o m
 *
 * @param fileName
 * @param outputFolder
 *
 * @throws java.io.FileNotFoundException
 */
public void unZipFolder(String fileName, String outputFolder) throws IOException {

    ZipFile zipFile = new ZipFile(fileName);
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        File entryDestination = new File(outputFolder, entry.getName());
        entryDestination.getParentFile().mkdirs();
        if (entry.isDirectory()) {
            //FileHelper fileHelper = new FileHelper();
            //String filename = fileHelper.getUniqueFileName(outputFolder, FilenameUtils.removeExtension(entry.getName()));
            //System.out.println("zip :" + filename);
            //new File(filename).mkdirs();

            entryDestination.mkdirs();

        } else {
            InputStream in = zipFile.getInputStream(entry);
            OutputStream out = new FileOutputStream(entryDestination);
            IOUtils.copy(in, out);
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
    }

    zipFile.close();
    this.deleteZipFile(fileName);
    System.out.println("Done");

}

From source file:com.oprisnik.semdroid.Semdroid.java

protected void extract(InputStream source, File targetDir) {
    if (!targetDir.exists()) {
        targetDir.mkdirs();/*w  w w .j av a  2  s . co m*/
    }
    if (BuildConfig.DEBUG) {
        Log.d(TAG, "Extracting to " + targetDir);
    }

    try {
        ZipInputStream zip = new ZipInputStream(source);
        ZipEntry entry = null;

        while ((entry = zip.getNextEntry()) != null) {
            if (entry.isDirectory()) {
                File dir = new File(targetDir, entry.getName());
                if (!dir.exists()) {
                    dir.mkdirs();
                }
            } else {
                File newFile = new File(targetDir, entry.getName());
                FileOutputStream fout = new FileOutputStream(newFile);
                if (BuildConfig.DEBUG) {
                    Log.d(TAG, "Extracting " + entry.getName() + " to " + newFile);
                }

                byte[] data = new byte[BUFFER];
                int count;
                while ((count = zip.read(data, 0, BUFFER)) != -1) {
                    fout.write(data, 0, count);
                }
                zip.closeEntry();
                fout.close();
            }

        }
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
    } finally {
        IOUtils.closeQuietly(source);
    }
}

From source file:com.seer.datacruncher.spring.ValidateFilePopupController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String idSchema = request.getParameter("idSchema");
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile multipartFile = multipartRequest.getFile("file");
    String resMsg = "";

    if (multipartFile.getOriginalFilename().endsWith(FileExtensionType.ZIP.getAbbreviation())) {
        // Case 1: When user upload a Zip file - All ZIP entries should be validate one by one      
        ZipInputStream inStream = null;
        try {//from w  w  w .jav  a 2s  .  c  o m
            inStream = new ZipInputStream(multipartFile.getInputStream());
            ZipEntry entry;
            while (!(isStreamClose(inStream)) && (entry = inStream.getNextEntry()) != null) {
                if (!entry.isDirectory()) {
                    DatastreamsInput datastreamsInput = new DatastreamsInput();
                    datastreamsInput.setUploadedFileName(entry.getName());
                    byte[] byteInput = IOUtils.toByteArray(inStream);
                    resMsg += datastreamsInput.datastreamsInput(new String(byteInput), Long.parseLong(idSchema),
                            byteInput);
                }
                inStream.closeEntry();
            }
        } catch (IOException ex) {
            resMsg = "Error occured during fetch records from ZIP file.";
        } finally {
            if (inStream != null)
                inStream.close();
        }
    } else {
        // Case 1: When user upload a single file. In this cae just validate a single stream 
        String datastream = new String(multipartFile.getBytes());
        DatastreamsInput datastreamsInput = new DatastreamsInput();
        datastreamsInput.setUploadedFileName(multipartFile.getOriginalFilename());

        resMsg = datastreamsInput.datastreamsInput(datastream, Long.parseLong(idSchema),
                multipartFile.getBytes());

    }
    String msg = resMsg.replaceAll("'", "\"").replaceAll("\\n", " ");
    msg = msg.trim();
    response.setContentType("text/html");
    ServletOutputStream out = null;
    out = response.getOutputStream();
    out.write(("{success: " + true + " , message:'" + msg + "',   " + "}").getBytes());
    out.flush();
    out.close();
    return null;
}