List of usage examples for java.util.zip ZipFile close
public void close() throws IOException
From source file:org.mule.util.FileUtils.java
/** * Unzip the specified archive to the given directory */// w w w .j av a 2s . c om public static void unzip(File archive, File directory) throws IOException { ZipFile zip = null; if (directory.exists()) { if (!directory.isDirectory()) { throw new IOException("Directory is not a directory: " + directory); } } else { if (!directory.mkdirs()) { throw new IOException("Could not create directory: " + directory); } } try { zip = new ZipFile(archive); for (Enumeration entries = zip.entries(); entries.hasMoreElements();) { ZipEntry entry = (ZipEntry) entries.nextElement(); File f = FileUtils.newFile(directory, entry.getName()); if (entry.isDirectory()) { if (!f.exists() && !f.mkdirs()) { throw new IOException("Could not create directory: " + f); } } else { InputStream is = zip.getInputStream(entry); OutputStream os = new BufferedOutputStream(new FileOutputStream(f)); IOUtils.copy(is, os); IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } } } finally { if (zip != null) { zip.close(); } } }
From source file:org.devproof.portal.core.module.theme.service.ThemeServiceImpl.java
@Override public void install(File themeArchive) { String uuid = UUID.randomUUID().toString(); try {//from w ww.j av a2s.c o m File folder = new File(servletContext.getRealPath("/WEB-INF/themes")); folder = new File(folder.toString() + File.separator + uuid); FileUtils.forceMkdir(folder); ZipFile zipFile = new ZipFile(themeArchive); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); File out = new File(folder.getAbsolutePath() + File.separator + entry.getName()); if (entry.isDirectory()) { FileUtils.forceMkdir(out); } else { FileUtils.touch(out); FileOutputStream fos = new FileOutputStream(out, false); IOUtils.copy(zipFile.getInputStream(entry), fos); fos.close(); } } zipFile.close(); logger.info("New theme installed: " + uuid); } catch (MalformedURLException e) { logger.warn("Unknown error", e); } catch (IOException e) { logger.warn("Unknown error", e); } }
From source file:com.samczsun.helios.LoadedFile.java
public void reset() throws IOException { files.clear();/*from w ww.ja v a2 s . co m*/ classes.clear(); ZipFile zipFile = null; try { zipFile = new ZipFile(file); Enumeration<? extends ZipEntry> enumeration = zipFile.entries(); while (enumeration.hasMoreElements()) { ZipEntry zipEntry = enumeration.nextElement(); if (!zipEntry.isDirectory()) { load(zipEntry.getName(), zipFile.getInputStream(zipEntry)); } } } catch (ZipException e) { //Probably not a ZIP file FileInputStream inputStream = null; try { inputStream = new FileInputStream(file); load(this.name, inputStream); } finally { if (inputStream != null) { inputStream.close(); } } } finally { if (zipFile != null) { try { zipFile.close(); } catch (IOException e) { } } } }
From source file:com.stevpet.sonar.plugins.dotnet.mscover.codecoverage.command.ZipUtils.java
/** * Extracts the specified folder from the specified archive, into the supplied output directory. * /*from w w w. j av a2 s . c o m*/ * @param archivePath * the archive Path * @param folderToExtract * the folder to extract * @param outputDirectory * the output directory * @return the extracted folder path * @throws IOException * if a problem occurs while extracting */ public static File extractArchiveFolderIntoDirectory(String archivePath, String folderToExtract, String outputDirectory) throws IOException { File destinationFolder = new File(outputDirectory); destinationFolder.mkdirs(); ZipFile zip = null; try { zip = new ZipFile(new File(archivePath)); Enumeration<?> zipFileEntries = zip.entries(); // Process each entry while (zipFileEntries.hasMoreElements()) { ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); String currentEntry = entry.getName(); if (currentEntry.startsWith(folderToExtract)) { File destFile = new File(destinationFolder, currentEntry); destFile.getParentFile().mkdirs(); if (!entry.isDirectory()) { BufferedInputStream is = null; BufferedOutputStream dest = null; try { is = new BufferedInputStream(zip.getInputStream(entry)); int currentByte; // establish buffer for writing file byte data[] = new byte[BUFFER_SIZE]; // write the current file to disk FileOutputStream fos = new FileOutputStream(destFile); dest = new BufferedOutputStream(fos, BUFFER_SIZE); // read and write until last byte is encountered while ((currentByte = is.read(data, 0, BUFFER_SIZE)) != -1) { dest.write(data, 0, currentByte); } } finally { if (dest != null) { dest.flush(); } IOUtils.closeQuietly(dest); IOUtils.closeQuietly(is); } } } } } finally { if (zip != null) { zip.close(); } } return new File(destinationFolder, folderToExtract); }
From source file:biz.c24.io.spring.batch.writer.C24ItemWriterTests.java
@Test public void testZipFileWrite() throws Exception { // Get somewhere temporary to write out to File outputFile = File.createTempFile("ItemWriterTest-", ".csv.zip"); outputFile.deleteOnExit();/* w ww. j a va 2s. co m*/ String outputFileName = outputFile.getAbsolutePath(); // Configure the ItemWriter C24ItemWriter itemWriter = new C24ItemWriter(); itemWriter.setSink(new TextualSink()); itemWriter.setWriterSource(new ZipFileWriterSource()); itemWriter.setup(getStepExecution(outputFileName)); // Write the employees out itemWriter.write(employees); // Close the file itemWriter.cleanup(); // Check that we wrote out what was expected ZipFile zipFile = new ZipFile(outputFileName); Enumeration<? extends ZipEntry> entries = zipFile.entries(); assertNotNull(entries); // Make sure there's at least one entry assertTrue(entries.hasMoreElements()); ZipEntry entry = entries.nextElement(); // Make sure that the trailing .zip has been removed and the leading path has been removed assertFalse(entry.getName().contains(System.getProperty("file.separator"))); assertFalse(entry.getName().endsWith(".zip")); // Make sure that there aren't any other entries assertFalse(entries.hasMoreElements()); try { compareCsv(zipFile.getInputStream(entry), employees); } finally { if (zipFile != null) { zipFile.close(); } } }
From source file:biz.c24.io.spring.batch.writer.C24ItemWriterTests.java
@Test public void testResourceZipFileWrite() throws Exception { // Get somewhere temporary to write out to File outputFile = File.createTempFile("ItemWriterTest-", ".csv.zip"); outputFile.deleteOnExit();/* w ww. j ava 2s. co m*/ String outputFileName = outputFile.getAbsolutePath(); ZipFileWriterSource source = new ZipFileWriterSource(); source.setResource(new FileSystemResource(outputFileName)); // Configure the ItemWriter C24ItemWriter itemWriter = new C24ItemWriter(); itemWriter.setSink(new TextualSink()); itemWriter.setWriterSource(source); itemWriter.setup(getStepExecution(null)); // Write the employees out itemWriter.write(employees); // Close the file itemWriter.cleanup(); // Check that we wrote out what was expected ZipFile zipFile = new ZipFile(outputFileName); Enumeration<? extends ZipEntry> entries = zipFile.entries(); assertNotNull(entries); // Make sure there's at least one entry assertTrue(entries.hasMoreElements()); ZipEntry entry = entries.nextElement(); // Make sure that the trailing .zip has been removed and the leading path has been removed assertFalse(entry.getName().contains(System.getProperty("file.separator"))); assertFalse(entry.getName().endsWith(".zip")); // Make sure that there aren't any other entries assertFalse(entries.hasMoreElements()); try { compareCsv(zipFile.getInputStream(entry), employees); } finally { if (zipFile != null) { zipFile.close(); } } }
From source file:com.enioka.jqm.tools.LibraryCache.java
private void loadCache(Node node, JobDef jd, EntityManager em) throws JqmPayloadException { jqmlogger.debug("Resolving classpath for job definition " + jd.getApplicationName()); File jarFile = new File(FilenameUtils.concat(new File(node.getRepo()).getAbsolutePath(), jd.getJarPath())); File jarDir = jarFile.getParentFile(); File libDir = new File(FilenameUtils.concat(jarDir.getAbsolutePath(), "lib")); File libDirExtracted = new File(FilenameUtils.concat(jarDir.getAbsolutePath(), "libFromJar")); File pomFile = new File(FilenameUtils.concat(jarDir.getAbsolutePath(), "pom.xml")); // POM file should be deleted if it comes from the jar file. Otherwise, it would stay into place and modifications to the internal // pom would be ignored. boolean pomFromJar = false; // 1st: if no pom, no lib dir => find a pom inside the JAR. (& copy it, we will read later) if (!pomFile.exists() && !libDir.exists()) { jqmlogger.trace("No pom inside jar directory. Checking for a pom inside the jar file"); InputStream is = null;/*from w w w .j a v a 2s . c om*/ FileOutputStream os = null; try { ZipFile zf = new ZipFile(jarFile); Enumeration<? extends ZipEntry> zes = zf.entries(); while (zes.hasMoreElements()) { ZipEntry ze = zes.nextElement(); if (ze.getName().endsWith("pom.xml")) { is = zf.getInputStream(ze); os = new FileOutputStream(pomFile); IOUtils.copy(is, os); pomFromJar = true; break; } } zf.close(); } catch (Exception e) { throw new JqmPayloadException("Could not handle pom inside jar", e); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } } // 2nd: no pom, no pom inside jar, no lib dir => find a lib dir inside the jar if (!pomFile.exists() && !libDir.exists()) { jqmlogger.trace("Checking for a lib directory inside jar"); InputStream is = null; FileOutputStream os = null; ZipFile zf = null; FileUtils.deleteQuietly(libDirExtracted); try { zf = new ZipFile(jarFile); Enumeration<? extends ZipEntry> zes = zf.entries(); while (zes.hasMoreElements()) { ZipEntry ze = zes.nextElement(); if (ze.getName().startsWith("lib/") && ze.getName().endsWith(".jar")) { if (!libDirExtracted.isDirectory() && !libDirExtracted.mkdir()) { throw new JqmPayloadException("Could not extract libraries from jar"); } is = zf.getInputStream(ze); os = new FileOutputStream(FilenameUtils.concat(libDirExtracted.getAbsolutePath(), FilenameUtils.getName(ze.getName()))); IOUtils.copy(is, os); IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } } } catch (Exception e) { throw new JqmPayloadException("Could not handle internal lib directory", e); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); try { zf.close(); } catch (Exception e) { jqmlogger.warn("could not close jar file", e); } } // If libs were extracted, put in cache and return if (libDirExtracted.isDirectory()) { FileFilter fileFilter = new WildcardFileFilter("*.jar"); File[] files = libDirExtracted.listFiles(fileFilter); URL[] libUrls = new URL[files.length]; try { for (int i = 0; i < files.length; i++) { libUrls[i] = files[i].toURI().toURL(); } } catch (Exception e) { throw new JqmPayloadException("Could not handle internal lib directory", e); } // Put in cache putInCache(libUrls, jd.getApplicationName()); return; } } // 3rd: if pom, use pom! if (pomFile.exists() && !libDir.exists()) { jqmlogger.trace("Reading a pom file"); // Retrieve resolver configuration List<GlobalParameter> repolist = em .createQuery("SELECT gp FROM GlobalParameter gp WHERE gp.key = :repo", GlobalParameter.class) .setParameter("repo", "mavenRepo").getResultList(); List<GlobalParameter> settings = em .createQuery("SELECT gp FROM GlobalParameter gp WHERE gp.key = :k", GlobalParameter.class) .setParameter("k", "mavenSettingsCL").getResultList(); List<GlobalParameter> settingFiles = em .createQuery("SELECT gp FROM GlobalParameter gp WHERE gp.key = :k", GlobalParameter.class) .setParameter("k", "mavenSettingsFile").getResultList(); boolean withCentral = false; String withCustomSettings = null; String withCustomSettingsFile = null; if (settings.size() == 1 && settingFiles.isEmpty()) { jqmlogger.trace("Custom settings file will be used: " + settings.get(0).getValue()); withCustomSettings = settings.get(0).getValue(); } if (settingFiles.size() == 1) { jqmlogger.trace("Custom settings file will be used: " + settingFiles.get(0).getValue()); withCustomSettingsFile = settingFiles.get(0).getValue(); } // Configure resolver ConfigurableMavenResolverSystem resolver = Maven.configureResolver(); if (withCustomSettings != null && withCustomSettingsFile == null) { resolver.fromClassloaderResource(withCustomSettings); } if (withCustomSettingsFile != null) { resolver.fromFile(withCustomSettingsFile); } for (GlobalParameter gp : repolist) { if (gp.getValue().contains("repo1.maven.org")) { withCentral = true; } resolver = resolver.withRemoteRepo(MavenRemoteRepositories .createRemoteRepository(gp.getId().toString(), gp.getValue(), "default") .setUpdatePolicy(MavenUpdatePolicy.UPDATE_POLICY_NEVER)); } resolver.withMavenCentralRepo(withCentral); // Resolve File[] depFiles = null; try { depFiles = resolver.loadPomFromFile(pomFile).importRuntimeDependencies().resolve() .withTransitivity().asFile(); } catch (IllegalArgumentException e) { // Happens when no dependencies inside pom, which is a weird use of the feature... jqmlogger.trace("No dependencies inside pom.xml file - no libs will be used", e); depFiles = new File[0]; } // Extract results int size = 0; for (File artifact : depFiles) { if (!"pom".equals(FilenameUtils.getExtension(artifact.getName()))) { size++; } } URL[] tmp = new URL[size]; int i = 0; for (File artifact : depFiles) { if ("pom".equals(FilenameUtils.getExtension(artifact.getName()))) { continue; } try { tmp[i] = artifact.toURI().toURL(); } catch (MalformedURLException e) { throw new JqmPayloadException("Incorrect dependency in POM file", e); } i++; } // Put in cache putInCache(tmp, jd.getApplicationName()); // Cleanup if (pomFromJar && !pomFile.delete()) { jqmlogger.warn("Could not delete the temp pom file extracted from the jar."); } return; } // 4: if lib, use lib... (lib has priority over pom) if (libDir.exists()) { jqmlogger.trace( "Using the lib directory " + libDir.getAbsolutePath() + " as the source for dependencies"); FileFilter fileFilter = new WildcardFileFilter("*.jar"); File[] files = libDir.listFiles(fileFilter); URL[] tmp = new URL[files.length]; for (int i = 0; i < files.length; i++) { try { tmp[i] = files[i].toURI().toURL(); } catch (MalformedURLException e) { throw new JqmPayloadException("incorrect file inside lib directory", e); } } // Put in cache putInCache(tmp, jd.getApplicationName()); return; } throw new JqmPayloadException( "There is no lib dir or no pom.xml inside the directory containing the jar or inside the jar. The jar cannot be launched."); }
From source file:org.roda.common.certification.ODFSignatureUtils.java
private static ByteArrayOutputStream addSignatureToStream(ZipFile zipFile, Element rootManifest, Element rootSignatures) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(baos); Enumeration<?> enumeration; for (enumeration = zipFile.entries(); enumeration.hasMoreElements();) { ZipEntry zeOut = (ZipEntry) enumeration.nextElement(); String fileName = zeOut.getName(); if (!fileName.equals(META_INF_DOCUMENTSIGNATURES_XML) && !fileName.equals("META-INF/manifest.xml")) { zos.putNextEntry(zeOut);//from w w w . j a va2 s .c o m InputStream is = zipFile.getInputStream(zipFile.getEntry(fileName)); zos.write(IOUtils.toByteArray(is)); zos.closeEntry(); IOUtils.closeQuietly(is); } } ZipEntry zeDocumentSignatures = new ZipEntry(META_INF_DOCUMENTSIGNATURES_XML); zos.putNextEntry(zeDocumentSignatures); ByteArrayOutputStream baosXML = new ByteArrayOutputStream(); writeXML(baosXML, rootSignatures, false); zos.write(baosXML.toByteArray()); zos.closeEntry(); baosXML.close(); ZipEntry zeManifest = new ZipEntry("META-INF/manifest.xml"); zos.putNextEntry(zeManifest); ByteArrayOutputStream baosManifest = new ByteArrayOutputStream(); writeXML(baosManifest, rootManifest, false); zos.write(baosManifest.toByteArray()); zos.closeEntry(); baosManifest.close(); zos.close(); zipFile.close(); return baos; }
From source file:eionet.gdem.utils.ZipUtil.java
/** * Unzips files to output directory.//from w w w . j a va 2 s. co m * @param inZip Zip file * @param outDir Output directory * @throws IOException If an error occurs. */ public static void unzip(String inZip, String outDir) throws IOException { File sourceZipFile = new File(inZip); File unzipDestinationDirectory = new File(outDir); // Open Zip file for reading ZipFile zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ); // Create an enumeration of the entries in the zip file Enumeration zipFileEntries = zipFile.entries(); // Process each entry while (zipFileEntries.hasMoreElements()) { // grab a zip file entry ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); String currentEntry = entry.getName(); // System.out.println("Extracting: " + entry); File destFile = new File(unzipDestinationDirectory, currentEntry); // grab file's parent directory structure File destinationParent = destFile.getParentFile(); // create the parent directory structure if needed destinationParent.mkdirs(); // extract file if not a directory if (!entry.isDirectory()) { BufferedInputStream is = null; BufferedOutputStream dest = null; try { is = new BufferedInputStream(zipFile.getInputStream(entry)); int currentByte; // establish buffer for writing file byte[] data = new byte[BUFFER]; // write the current file to disk FileOutputStream fos = new FileOutputStream(destFile); dest = new BufferedOutputStream(fos, BUFFER); // read and write until last byte is encountered while ((currentByte = is.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, currentByte); } } finally { IOUtils.closeQuietly(dest); IOUtils.closeQuietly(is); } } } zipFile.close(); }
From source file:org.eclipse.mylyn.commons.sdk.util.CommonTestUtil.java
private static void unzip(ZipFile zipFile, File rootDstDir, File dstDir, int depth) throws IOException { Enumeration<? extends ZipEntry> entries = zipFile.entries(); try {//w ww . j a v a 2s.com 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) { // don't need to catch this } } if (src != null) { try { src.close(); } catch (IOException e) { // don't need to catch this } } } } } finally { try { zipFile.close(); } catch (IOException e) { // don't need to catch this } } }