List of usage examples for java.util.zip ZipEntry getSize
public long getSize()
From source file:org.openspaces.core.util.FileUtils.java
public static byte[] unzipFileToMemory(String applicationFile, File directoryOrZip, long maxFileSizeInBytes) { ZipFile zipFile = null;/* w ww .j a v a 2s . c o m*/ try { zipFile = new ZipFile(directoryOrZip); final ZipEntry zipEntry = zipFile.getEntry(applicationFile); if (zipEntry == null) { throw new RuntimeException("Failed to load " + applicationFile + " from " + directoryOrZip); } final int length = (int) zipEntry.getSize(); if (length > maxFileSizeInBytes) { throw new RuntimeException( applicationFile + " file size cannot be bigger than " + maxFileSizeInBytes + " bytes"); } byte[] buffer = new byte[length]; final InputStream in = zipFile.getInputStream(zipEntry); final DataInputStream din = new DataInputStream(in); try { din.readFully(buffer, 0, length); return buffer; } catch (final IOException e) { throw new RuntimeException("Failed to read application file input stream", e); } } catch (final IOException e) { throw new RuntimeException("Failed to read zip file " + directoryOrZip, e); } finally { if (zipFile != null) { try { zipFile.close(); } catch (final IOException e) { logger.debug("Failed to close zip file " + directoryOrZip, e); } } } }
From source file:org.opf_labs.fmts.corpora.govdocs.GovDocs.java
private static final FolderDetails getZipFolderDetails(final File zipFolder) throws ZipException, IOException { ZipFile zipFile = new ZipFile(zipFolder); Enumeration<? extends ZipEntry> entries = zipFile.entries(); ZipEntry entry = null; int count = 0; long size = 0L; final Set<String> exts = new HashSet<String>(); while (entries.hasMoreElements()) { entry = entries.nextElement();/*from ww w. j av a 2 s . co m*/ if (!entry.isDirectory()) { count++; size += entry.getSize(); exts.add(FilenameUtils.getExtension(entry.getName())); } } zipFile.close(); FolderDetails dets = new FolderDetails(count, size, exts); return dets; }
From source file:io.github.bonigarcia.wdm.Downloader.java
public static final File extract(File compressedFile, String export) throws IOException { log.trace("Compressed file {}", compressedFile); File file = null;// w w w . jav a 2s . c o m if (compressedFile.getName().toLowerCase().endsWith("tar.bz2")) { file = unBZip2(compressedFile); } else if (compressedFile.getName().toLowerCase().endsWith("tar.gz")) { file = unTarGz(compressedFile); } else if (compressedFile.getName().toLowerCase().endsWith("gz")) { file = unGzip(compressedFile); } else { ZipFile zipFolder = new ZipFile(compressedFile); Enumeration<?> enu = zipFolder.entries(); while (enu.hasMoreElements()) { ZipEntry zipEntry = (ZipEntry) enu.nextElement(); String name = zipEntry.getName(); long size = zipEntry.getSize(); long compressedSize = zipEntry.getCompressedSize(); log.trace("Unzipping {} (size: {} KB, compressed size: {} KB)", name, size, compressedSize); file = new File(compressedFile.getParentFile() + File.separator + name); if (!file.exists() || WdmConfig.getBoolean("wdm.override")) { if (name.endsWith("/")) { file.mkdirs(); continue; } File parent = file.getParentFile(); if (parent != null) { parent.mkdirs(); } InputStream is = zipFolder.getInputStream(zipEntry); FileOutputStream fos = new FileOutputStream(file); byte[] bytes = new byte[1024]; int length; while ((length = is.read(bytes)) >= 0) { fos.write(bytes, 0, length); } is.close(); fos.close(); file.setExecutable(true); } else { log.debug(file + " already exists"); } } zipFolder.close(); } file = checkPhantom(compressedFile, export); log.trace("Resulting binary file {}", file.getAbsoluteFile()); return file.getAbsoluteFile(); }
From source file:de.ingrid.importer.udk.util.Zipper.java
/** * Extracts the given ZIP-File and return a vector containing String * representation of the extracted files. * //from www . ja v a2s. c o m * @param zipFileName * the name of the ZIP-file * @param targetDir * the target directory * @param keepSubfolders * boolean parameter, whether to keep the folder structure * * @return a Vector<String> containing String representation of the allowed * files from the ZipperFilter. * @return null if the input data was invalid or an Exception occurs */ public static final List<String> extractZipFile(InputStream myInputStream, final String targetDir, final boolean keepSubfolders, ZipperFilter zipperFilter) { if (log.isDebugEnabled()) { log.debug("extractZipFile: inputStream=" + myInputStream + ", targetDir='" + targetDir + "', keepSubfolders=" + keepSubfolders); } ArrayList<String> extractedFiles = new ArrayList<String>(); FileOutputStream fos = null; File outdir = new File(targetDir); // make some checks if (outdir.isFile()) { String msg = "The Target Directory \"" + outdir + "\" must not be a file ."; log.error(msg); System.err.println(msg); return null; } // create necessary directories for the output directory outdir.mkdirs(); // Start Unzipping ... try { if (log.isDebugEnabled()) { log.debug("Start unzipping"); } ZipInputStream zis = new ZipInputStream(myInputStream); if (log.isDebugEnabled()) { log.debug("ZipInputStream from InputStream=" + zis); } // for every zip-entry ZipEntry zEntry; String name; while ((zEntry = zis.getNextEntry()) != null) { name = zEntry.toString(); if (log.isDebugEnabled()) { log.debug("Zip Entry name: " + name + ", size:" + zEntry.getSize()); } boolean isDir = name.endsWith(separator); // System.out.println("------------------------------"); // System.out.println((isDir? "<d>":"< >")+name); String[] nameSplitted = name.split(separator); // If it's a File, take all Splitted Names except the last one int len = (isDir ? nameSplitted.length : nameSplitted.length - 1); String currStr = targetDir; if (keepSubfolders) { // create all directories from the entry for (int j = 0; j < len; j++) { // System.out.println("Dirs: " + nameSplitted[j]); currStr += nameSplitted[j] + File.separator; // System.out.println("currStr: "+currStr); File currDir = new File(currStr); currDir.mkdirs(); } } // if the entry is a file, then create it. if (!isDir) { // set the file name of the output file. String outputFileName = null; if (keepSubfolders) { outputFileName = currStr + nameSplitted[nameSplitted.length - 1]; } else { outputFileName = targetDir + nameSplitted[nameSplitted.length - 1]; } File outputFile = new File(outputFileName); fos = new FileOutputStream(outputFile); // write the File if (log.isDebugEnabled()) { log.debug("Write Zip Entry '" + name + "' to file '" + outputFile + "'"); } writeFile(zis, fos, buffersize); if (log.isDebugEnabled()) { log.debug("FILE WRITTEN: " + outputFile.getAbsolutePath()); } // add the file to the vector to be returned if (zipperFilter != null) { String[] accFiles = zipperFilter.getAcceptedFiles(); String currFileName = outputFile.getAbsolutePath(); for (int i = 0; i < accFiles.length; i++) { if (currFileName.endsWith(accFiles[i])) { extractedFiles.add(currFileName); } } } else { extractedFiles.add(outputFile.getAbsolutePath()); } } } // end while zis.close(); } catch (Exception e) { log.error("Problems unzipping file", e); e.printStackTrace(); return null; } return extractedFiles; }
From source file:de.rub.syssec.saaf.analysis.steps.extract.ApkUnzipper.java
/** * Extracts the given apk into the given destination directory * // w w w . j a v a 2 s .com * @param archive * - the file to extract * @param dest * - the destination directory * @throws IOException */ public static void extractApk(File archive, File dest) throws IOException { @SuppressWarnings("resource") // Closing it later results in an error ZipFile zipFile = new ZipFile(archive); Enumeration<? extends ZipEntry> entries = zipFile.entries(); BufferedOutputStream bos = null; BufferedInputStream bis = null; while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); String entryFileName = entry.getName(); byte[] buffer = new byte[16384]; int len; File dir = buildDirectoryHierarchyFor(entryFileName, dest);// destDir if (!dir.exists()) { dir.mkdirs(); } if (!entry.isDirectory()) { if (entry.getSize() == 0) { LOGGER.warn("Found ZipEntry \'" + entry.getName() + "\' with size 0 in " + archive.getName() + ". Looks corrupted."); continue; } try { bos = new BufferedOutputStream(new FileOutputStream(new File(dest, entryFileName)));// destDir,... bis = new BufferedInputStream(zipFile.getInputStream(entry)); while ((len = bis.read(buffer)) > 0) { bos.write(buffer, 0, len); } bos.flush(); } catch (IOException ioe) { LOGGER.warn("Failed to extract entry \'" + entry.getName() + "\' from archive. Results for " + archive.getName() + " may not be accurate"); } finally { if (bos != null) bos.close(); if (bis != null) bis.close(); // if (zipFile != null) zipFile.close(); } } } }
From source file:org.roda.common.certification.ODFSignatureUtils.java
public static void runDigitalSignatureStrip(Path input, Path output) throws IOException { OutputStream os = new FileOutputStream(output.toFile()); BufferedOutputStream bos = new BufferedOutputStream(os); ZipOutputStream zout = new ZipOutputStream(bos); ZipFile zipFile = new ZipFile(input.toString()); Enumeration<?> enumeration; for (enumeration = zipFile.entries(); enumeration.hasMoreElements();) { ZipEntry entry = (ZipEntry) enumeration.nextElement(); String entryName = entry.getName(); if (!META_INF_DOCUMENTSIGNATURES_XML.equalsIgnoreCase(entryName) && entry.getSize() > 0) { InputStream zipStream = zipFile.getInputStream(entry); ZipEntry destEntry = new ZipEntry(entryName); zout.putNextEntry(destEntry); byte[] data = new byte[(int) entry.getSize()]; while ((zipStream.read(data, 0, (int) entry.getSize())) != -1) { }//from w ww . j av a 2 s. c om zout.write(data); zout.closeEntry(); IOUtils.closeQuietly(zipStream); } } IOUtils.closeQuietly(zout); IOUtils.closeQuietly(bos); IOUtils.closeQuietly(os); zipFile.close(); }
From source file:org.roda.core.plugins.plugins.characterization.ODFSignatureUtils.java
public static void runDigitalSignatureStrip(Path input, Path output) throws IOException { BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(output.toFile())); try (ZipFile zipFile = new ZipFile(input.toString()); ZipOutputStream zout = new ZipOutputStream(bos)) { Enumeration<?> enumeration; for (enumeration = zipFile.entries(); enumeration.hasMoreElements();) { ZipEntry entry = (ZipEntry) enumeration.nextElement(); String entryName = entry.getName(); if (!META_INF_DOCUMENTSIGNATURES_XML.equalsIgnoreCase(entryName) && entry.getSize() > 0) { try (InputStream zipStream = zipFile.getInputStream(entry)) { ZipEntry destEntry = new ZipEntry(entryName); zout.putNextEntry(destEntry); byte[] data = new byte[(int) entry.getSize()]; while ((zipStream.read(data, 0, (int) entry.getSize())) != -1) { }/*from ww w .j av a2 s.c om*/ zout.write(data); zout.closeEntry(); } } } } }
From source file:com.vmware.admiral.closures.util.ClosureUtils.java
private static void buildTarData(URL dirURL, String folderNameFilter, OutputStream outputStream) throws IOException { final JarURLConnection jarConnection = (JarURLConnection) dirURL.openConnection(); final ZipFile jar = jarConnection.getJarFile(); final Enumeration<? extends ZipEntry> entries = jar.entries(); try (TarArchiveOutputStream tarArchiveOutputStream = buildTarStream(outputStream)) { while (entries.hasMoreElements()) { final ZipEntry entry = entries.nextElement(); final String name = entry.getName(); if (!name.startsWith(folderNameFilter)) { // entry in wrong subdir -- don't copy continue; }/*w ww .j a v a 2s . c o m*/ TarArchiveEntry tarEntry = new TarArchiveEntry(entry.getName().replaceAll(folderNameFilter, "")); try (InputStream is = jar.getInputStream(entry)) { putTarEntry(tarArchiveOutputStream, tarEntry, is, entry.getSize()); } } tarArchiveOutputStream.flush(); tarArchiveOutputStream.close(); } }
From source file:org.sweble.wikitext.engine.MassExpansionTest.java
private static NamedParametrizedSuite enumerateSuiteTestCasesFromZip(File zipFile) throws IOException { ZipFile zf = new ZipFile(zipFile); try {//from w w w. j a va2 s . c o m Enumeration<? extends ZipEntry> entries = zf.entries(); String suiteName; { String zfname = zipFile.getName(); if (!zfname.toLowerCase().endsWith(".zip")) throw new InternalError(); suiteName = zfname.substring(0, zfname.length() - 4); } String testPrefix = suiteName + "/tests/"; String resourcesPrefix = suiteName + "/resources/"; Map<FileUrlKey, String> fileUrls = new HashMap<FileUrlKey, String>(); Map<String, ArticleDesc> articles = new HashMap<String, ArticleDesc>(); List<Object[]> testCases = new ArrayList<Object[]>(); while (entries.hasMoreElements()) { ZipEntry ze = (ZipEntry) entries.nextElement(); // Skip directories if (ze.getName().endsWith("/")) continue; long longSize = ze.getSize(); if (longSize > Integer.MAX_VALUE) throw new IllegalArgumentException("Archives contains files too big to process!"); InputStream is = zf.getInputStream(ze); byte[] content = IOUtils.toByteArray(is); is.close(); String filename = ze.getName(); if (filename.startsWith(resourcesPrefix + "fileUrl-") && filename.endsWith(".txt")) { filename = filename.substring(resourcesPrefix.length()); Matcher m = FILE_URL_RX.matcher(filename); if (!m.matches()) throw new IllegalArgumentException("Wrong 'fileUrl' pattern: " + ze.getName()); String encName = m.group(1); int width = Integer.parseInt(m.group(2)); int height = Integer.parseInt(m.group(3)); FileUrlKey key = new FileUrlKey(encName, width, height); fileUrls.put(key, new String(content, "UTF8")); } else if (filename.startsWith(resourcesPrefix + "retrieveWikitext-") && filename.endsWith(".wikitext")) { filename = filename.substring(resourcesPrefix.length()); Matcher m = ARTICLE_RX.matcher(filename); if (!m.matches()) throw new IllegalArgumentException("Wrong 'retrieveWikitext' pattern: " + ze.getName()); String encName = m.group(1); long revision = Long.parseLong(m.group(2)); ArticleDesc article = new ArticleDesc(revision, new String(content, "UTF8")); articles.put(encName, article); } else if (filename.startsWith(testPrefix) && filename.endsWith(".txt")) { filename = filename.substring(testPrefix.length()); Matcher m = TEST_RX.matcher(filename); if (!m.matches()) throw new IllegalArgumentException("Invalid test case filename: " + ze.getName()); String title = m.group(1); String test = new String(content, "UTF8"); testCases.add(new Object[] { title, fileUrls, articles, test }); } else { System.err.println("Ignored file in " + zipFile + ": " + ze.getName()); continue; } } Collections.sort(testCases, new Comparator<Object[]>() { @Override public int compare(Object[] o1, Object[] o2) { return ((String) o1[0]).compareTo((String) o2[0]); } }); return new NamedParametrizedSuite(zipFile.getName(), MassExpansionTest.class.getSimpleName(), testCases); } finally { zf.close(); } }
From source file:org.kalypso.commons.java.util.zip.ZipUtilities.java
/** * returns the {@link InputStream} for the file with given name in the given zipped file *///from ww w .j a v a 2 s .c o m public static InputStream getInputStreamForSingleFile(final URL zipFileURL, final String zippedFile) throws IOException, URISyntaxException { final ZipFile zf = new ZipFile(new File(zipFileURL.toURI())); final Enumeration<?> entries = zf.entries(); while (entries.hasMoreElements()) { final ZipEntry ze = (ZipEntry) entries.nextElement(); if (!ze.isDirectory() && (StringUtils.isBlank(zippedFile) || zippedFile.equalsIgnoreCase(ze.getName()))) { final long size = ze.getSize(); // FIXME: why this size check: dubios! if (size > 0) { return zf.getInputStream(ze); } } } return null; }