List of usage examples for java.util.zip ZipEntry isDirectory
public boolean isDirectory()
From source file:nl.nn.adapterframework.pipes.UnzipPipe.java
public PipeRunResult doPipe(Object input, IPipeLineSession session) throws PipeRunException { InputStream in;//www .j a v a2 s .c o m if (input instanceof InputStream) { in = (InputStream) input; } else { String filename = (String) input; try { in = new FileInputStream(filename); } catch (FileNotFoundException e) { throw new PipeRunException(this, "could not find file [" + filename + "]", e); } } String entryResults = ""; int count = 0; ZipInputStream zis = new ZipInputStream(new BufferedInputStream(in)); try { ZipEntry ze; while ((ze = zis.getNextEntry()) != null) { if (ze.isDirectory()) { if (isCreateSubdirectories()) { File tmpFile = new File(dir, ze.getName()); if (!tmpFile.exists()) { if (tmpFile.mkdirs()) { log.debug(getLogPrefix(session) + "created directory [" + tmpFile.getPath() + "]"); } else { log.warn(getLogPrefix(session) + "directory [" + tmpFile.getPath() + "] could not be created"); } } else { log.debug(getLogPrefix(session) + "directory entry [" + tmpFile.getPath() + "] already exists"); } } else { log.warn(getLogPrefix(session) + "skipping directory entry [" + ze.getName() + "]"); } } else { String filename = ze.getName(); String basename = null; String extension = null; int dotPos = filename.indexOf('.'); if (dotPos >= 0) { extension = filename.substring(dotPos); basename = filename.substring(0, dotPos); log.debug(getLogPrefix(session) + "parsed filename [" + basename + "] extension [" + extension + "]"); } else { basename = filename; } File tmpFile; if (isKeepOriginalFileName()) { tmpFile = new File(dir, filename); if (tmpFile.exists()) { throw new PipeRunException(this, "file [" + tmpFile.getAbsolutePath() + "] already exists"); } } else { tmpFile = File.createTempFile(basename, extension, dir); } if (isDeleteOnExit()) { tmpFile.deleteOnExit(); } if (isCreateSubdirectories()) { //extra check File tmpDir = tmpFile.getParentFile(); if (!tmpDir.exists()) { if (tmpDir.mkdirs()) { log.debug(getLogPrefix(session) + "created directory [" + tmpDir.getPath() + "]"); } else { log.warn(getLogPrefix(session) + "directory [" + tmpDir.getPath() + "] could not be created"); } } } FileOutputStream fos = new FileOutputStream(tmpFile); log.debug(getLogPrefix(session) + "writing ZipEntry [" + ze.getName() + "] to file [" + tmpFile.getPath() + "]"); count++; Misc.streamToStream(zis, fos, false); fos.close(); if (isCollectResults()) { entryResults += "<result item=\"" + count + "\"><zipEntry>" + XmlUtils.encodeCdataString(ze.getName()) + "</zipEntry><fileName>" + XmlUtils.encodeCdataString(tmpFile.getPath()) + "</fileName></result>"; } } } } catch (IOException e) { throw new PipeRunException(this, "cannot unzip", e); } finally { try { zis.close(); } catch (IOException e1) { log.warn(getLogPrefix(session) + "exception closing zip", e1); } } String result = "<results count=\"" + count + "\">" + entryResults + "</results>"; return new PipeRunResult(getForward(), result); }
From source file:br.univali.celine.lms.utils.zip.Zip.java
public void unzip(File zipFile, File dir) throws Exception { InputStream is = null;/*from ww w . jav a 2 s . c o m*/ OutputStream os = null; ZipFile zip = null; try { zip = new ZipFile(zipFile); Enumeration<? extends ZipEntry> e = zip.entries(); byte[] buffer = new byte[2048]; int currentEntry = 0; while (e.hasMoreElements()) { ZipEntry zipEntry = (ZipEntry) e.nextElement(); File file = new File(dir, zipEntry.getName()); currentEntry++; if (zipEntry.isDirectory()) { if (!file.exists()) file.mkdirs(); continue; } if (!file.getParentFile().exists()) file.getParentFile().mkdirs(); try { int bytesLidos = 0; is = zip.getInputStream(zipEntry); os = new FileOutputStream(file); if (is == null) throw new ZipException("Erro ao ler a entrada do zip: " + zipEntry.getName()); while ((bytesLidos = is.read(buffer)) > 0) os.write(buffer, 0, bytesLidos); if (listener != null) listener.unzip((100 * currentEntry) / zip.size()); } finally { if (is != null) try { is.close(); } catch (Exception ex) { } if (os != null) try { os.close(); } catch (Exception ex) { } } } } finally { if (zip != null) try { zip.close(); } catch (Exception e) { } } }
From source file:org.bsc.maven.plugin.findclass.ClasspathDescriptor.java
private void addArchive(final File element) throws IOException { if (addCached(element)) { return;/*from www . j ava 2 s.c om*/ } final List<String> classes = new ArrayList<>(); final List<String> resources = new ArrayList<>(); InputStream input = null; ZipInputStream zipInput = null; try { input = element.toURI().toURL().openStream(); zipInput = new ZipInputStream(input); ZipEntry entry; while ((entry = zipInput.getNextEntry()) != null) { if (!entry.isDirectory()) { final String name = entry.getName(); if ("class".equals(FilenameUtils.getExtension(name))) { final String className = FilenameUtils.removeExtension(name).replace('/', '.').replace('\\', '.'); classes.add(className); addClass(className, element); } else { final String resourcePath = name.replace('\\', File.separatorChar); resources.add(resourcePath); addResource(resourcePath, element); } } } CACHED_BY_ELEMENT.put(element, new Cached(classes, resources)); } finally { if (zipInput != null) { // this will also close the wrapped stream IOUtils.closeQuietly(zipInput); } else if (input != null) { IOUtils.closeQuietly(input); } } }
From source file:de.dfki.km.perspecting.obie.corpus.TextCorpus.java
/** * @return list of files in corpus/* w w w. j av a 2s .c o m*/ * @throws IOException * @throws ZipException */ @SuppressWarnings("unchecked") protected HashMap<URI, InputStream> getEntries() throws Exception { HashMap<URI, InputStream> entries = new HashMap<URI, InputStream>(); if (corpusFileMediaType == MediaType.ZIP) { ZipFile zippedCorpusDir = new ZipFile(corpus); Enumeration<? extends ZipEntry> zipEntries = zippedCorpusDir.entries(); while (zipEntries.hasMoreElements()) { ZipEntry zipEntry = zipEntries.nextElement(); if (!zipEntry.isDirectory()) { String uriValue = corpus.toURI().toString() + "/"; String entryName = zipEntry.getName(); uriValue += URLEncoder.encode(entryName, "utf-8"); entries.put(new URI(uriValue), zippedCorpusDir.getInputStream(zipEntry)); } } } else if (corpusFileMediaType == MediaType.DIRECTORY) { for (File f : corpus.listFiles()) { entries.put(f.toURI(), new FileInputStream(f)); } } return entries; }
From source file:com.google.appinventor.buildserver.util.AARLibrary.java
/** * Unpacks the Android Archive to a directory in the file system. The unpacking operation will * create a new directory named with the archive's package name to prevent collisions with * other Android Archives./* w ww.ja va 2 s .co m*/ * @param path the path to where the archive will be unpacked. * @throws IOException if any error occurs attempting to read the archive or write new files to * the file system. */ public void unpackToDirectory(final File path) throws IOException { ZipFile zip = null; try { zip = new ZipFile(aarPath); packageName = extractPackageName(zip); basedir = new File(path, packageName); if (!basedir.mkdirs()) { throw new IOException("Unable to create directory for AAR package"); } InputStream input = null; OutputStream output = null; Enumeration<? extends ZipEntry> i = zip.entries(); while (i.hasMoreElements()) { ZipEntry entry = i.nextElement(); File target = new File(basedir, entry.getName()); if (entry.isDirectory() && !target.exists() && !target.mkdirs()) { throw new IOException("Unable to create directory " + path.getAbsolutePath()); } else if (!entry.isDirectory()) { try { output = new FileOutputStream(target); input = zip.getInputStream(entry); IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } catalog(target); } } resdir = new File(basedir, "res"); if (!resdir.exists()) { resdir = null; } } finally { IOUtils.closeQuietly(zip); } }
From source file:com.haulmont.cuba.web.controllers.StaticContentController.java
protected LookupResult lookupNoCache(HttpServletRequest req) { final String path = getPath(req); if (isForbidden(path)) return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden"); ServletContext context = req.getSession().getServletContext(); final URL url; try {//from ww w .ja va 2 s . com url = context.getResource(path); } catch (MalformedURLException e) { return new Error(HttpServletResponse.SC_BAD_REQUEST, "Malformed path"); } if (url == null) return new Error(HttpServletResponse.SC_NOT_FOUND, "Not found"); final String mimeType = getMimeType(path); final String realpath = context.getRealPath(path); if (realpath != null) { // Try as an ordinary file File f = new File(realpath); if (!f.isFile()) return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden"); else { return createLookupResult(req, f.lastModified(), mimeType, (int) f.length(), acceptsDeflate(req), url); } } else { try { // Try as a JAR Entry final ZipEntry ze = ((JarURLConnection) url.openConnection()).getJarEntry(); if (ze != null) { if (ze.isDirectory()) return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden"); else return createLookupResult(req, ze.getTime(), mimeType, (int) ze.getSize(), acceptsDeflate(req), url); } else // Unexpected? return new StaticFile(-1, mimeType, -1, acceptsDeflate(req), url); } catch (ClassCastException e) { // Unknown resource type return createLookupResult(req, -1, mimeType, -1, acceptsDeflate(req), url); } catch (IOException e) { return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error"); } } }
From source file:de.jcup.egradle.core.util.FileSupport.java
/** * Unzips the given zip file to the given destination directory extracting * only those entries the pass through the given filter. * * @param zipFile/* w w w . j a v a2 s. c o m*/ * the zip file to unzip * @param dstDir * the destination directory * @throws IOException * in case of problem */ public void unzip(ZipFile zipFile, File dstDir) throws IOException { Enumeration<? extends ZipEntry> entries = zipFile.entries(); try { while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) { continue; } String entryName = entry.getName(); File file = new File(dstDir, changeSeparator(entryName, '/', File.separatorChar)); file.getParentFile().mkdirs(); InputStream src = null; OutputStream dst = null; try { src = zipFile.getInputStream(entry); dst = new FileOutputStream(file); transferData(src, dst); } finally { if (dst != null) { try { dst.close(); } catch (IOException e) { } } if (src != null) { src.close(); } } } } finally { try { zipFile.close(); } catch (IOException e) { } } }
From source file:net.morimekta.providence.maven.plugin.BaseGenerateSourcesMojo.java
private void addDependencyInclude(File workingDir, Set<File> includes, Artifact artifact) throws MojoExecutionException { // TODO: Figure out if this is the right way to name the output directories. File outputDir = new File(workingDir, artifact.getGroupId().replaceAll("[.]", File.separator) + File.separator + artifact.getArtifactId()); if (!outputDir.exists()) { if (!outputDir.mkdirs()) { throw new MojoExecutionException("Unable to create output dir " + outputDir); }/* ww w. j av a 2 s. c o m*/ } try (FileInputStream fis = new FileInputStream(artifact.getFile()); BufferedInputStream bis = new BufferedInputStream(fis); ZipInputStream zis = new ZipInputStream(bis)) { ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { if (entry.isDirectory()) { zis.closeEntry(); continue; } File of = new File(outputDir, new File(entry.getName()).getName()); try (FileOutputStream fos = new FileOutputStream(of, false); BufferedOutputStream bos = new BufferedOutputStream(fos)) { IOUtils.copy(zis, bos); } zis.closeEntry(); } includes.add(outputDir); } catch (IOException e) { throw new MojoExecutionException("" + e.getMessage(), e); } }
From source file:org.apache.openmeetings.backup.BackupImport.java
private static File unzip(InputStream is) throws IOException { File f = OmFileHelper.getNewDir(OmFileHelper.getUploadImportDir(), "import_" + CalendarPatterns.getTimeForStreamId(new Date())); log.debug("##### EXTRACTING BACKUP TO: " + f); try (ZipInputStream zis = new ZipInputStream(is)) { ZipEntry zipentry = null; while ((zipentry = zis.getNextEntry()) != null) { // for each entry to be extracted File fentry = validate(zipentry.getName(), f); File dir = zipentry.isDirectory() ? fentry : fentry.getParentFile(); if (!dir.exists()) { if (!dir.mkdirs()) { log.warn("Failed to create folders: " + dir); }//from w w w . j av a2 s. co m } if (!fentry.isDirectory()) { FileHelper.copy(zis, fentry); zis.closeEntry(); } } } return f; }
From source file:biz.c24.io.spring.batch.reader.source.ZipFileSource.java
/** * Gets the next ZipEntry that isn't a directory * @return The next file-type ZipEntry, null if there isn't one *///from w w w.j a v a 2 s. c o m private synchronized ZipEntry getNextZipEntry() { ZipEntry next = null; while (next == null && zipEntries.hasMoreElements()) { next = zipEntries.nextElement(); if (next.isDirectory()) { next = null; } } return next; }