List of usage examples for java.util.zip ZipInputStream close
public void close() throws IOException
From source file:com.maxl.java.aips2sqlite.AllDown.java
private void unzipToTemp(File dst) { try {//from w ww . jav a 2s . c o m ZipInputStream zin = new ZipInputStream(new FileInputStream(dst)); String workingDir = "./downloads/tmp" + File.separator + "unzipped_tmp"; byte buffer[] = new byte[4096]; int bytesRead; ZipEntry entry = null; while ((entry = zin.getNextEntry()) != null) { String dirName = workingDir; int endIndex = entry.getName().lastIndexOf(File.separatorChar); if (endIndex != -1) { dirName += entry.getName().substring(0, endIndex); } File newDir = new File(dirName); // If the directory that this entry should be inflated under does not exist, create it if (!newDir.exists() && !newDir.mkdir()) { throw new ZipException("Could not create directory " + dirName + "\n"); } // Copy data from ZipEntry to file FileOutputStream fos = new FileOutputStream(workingDir + File.separator + entry.getName()); while ((bytesRead = zin.read(buffer)) != -1) { fos.write(buffer, 0, bytesRead); } fos.close(); } zin.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.thinkbiganalytics.feedmgr.service.template.ExportImportTemplateService.java
/** * Open the zip file and populate the {@link ImportTemplate} object with the components in the file/archive * * @param fileName the file name/* w w w .j a va 2 s . c om*/ * @param inputStream the file * @return the template data to import */ private ImportTemplate openZip(String fileName, InputStream inputStream) throws IOException { byte[] buffer = new byte[1024]; ZipInputStream zis = new ZipInputStream(inputStream); ZipEntry zipEntry; ImportTemplate importTemplate = new ImportTemplate(fileName); while ((zipEntry = zis.getNextEntry()) != null) { String zipEntryContents = ZipFileUtil.zipEntryToString(buffer, zis, zipEntry); if (zipEntry.getName().startsWith(NIFI_TEMPLATE_XML_FILE)) { importTemplate.setNifiTemplateXml(zipEntryContents); } else if (zipEntry.getName().startsWith(TEMPLATE_JSON_FILE)) { importTemplate.setTemplateJson(zipEntryContents); } else if (zipEntry.getName().startsWith(NIFI_CONNECTING_REUSABLE_TEMPLATE_XML_FILE)) { importTemplate.addNifiConnectingReusableTemplateXml(zipEntryContents); } } zis.closeEntry(); zis.close(); if (!importTemplate.hasValidComponents()) { throw new UnsupportedOperationException( " The file you uploaded is not a valid archive. Please ensure the Zip file has been exported from the system and has 2 valid files named: " + NIFI_TEMPLATE_XML_FILE + ", and " + TEMPLATE_JSON_FILE); } importTemplate.setZipFile(true); return importTemplate; }
From source file:se.bitcraze.crazyflielib.bootloader.Bootloader.java
public void unzip(File zipFile) { mLogger.debug("Trying to unzip " + zipFile + "..."); InputStream fis = null;// w ww . j a v a2 s . c om ZipInputStream zis = null; FileOutputStream fos = null; String parent = zipFile.getAbsoluteFile().getParent(); try { fis = new FileInputStream(zipFile); zis = new ZipInputStream(new BufferedInputStream(fis)); ZipEntry ze; while ((ze = zis.getNextEntry()) != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int count; while ((count = zis.read(buffer)) != -1) { baos.write(buffer, 0, count); } String filename = ze.getName(); byte[] bytes = baos.toByteArray(); // write files File filePath = new File(parent + "/" + getFileNameWithoutExtension(zipFile) + "/" + filename); // create subdir filePath.getParentFile().mkdirs(); fos = new FileOutputStream(filePath); fos.write(bytes); //check if (filePath.exists() && filePath.length() > 0) { mLogger.debug(filename + " successfully extracted to " + filePath.getAbsolutePath()); } else { mLogger.error(filename + " was not extracted."); } } } catch (FileNotFoundException ffe) { mLogger.error(ffe.getMessage()); } catch (IOException ioe) { mLogger.error(ioe.getMessage()); } finally { if (zis != null) { try { zis.close(); } catch (IOException e) { mLogger.error(e.getMessage()); } } if (fos != null) { try { fos.close(); } catch (IOException e) { mLogger.error(e.getMessage()); } } } }
From source file:org.jahia.utils.zip.JahiaArchiveFileHandler.java
public Map<String, String> unzip(String path, boolean overwrite, PathFilter pathFilter, String pathPrefix) throws JahiaException { Map<String, String> unzippedFiles = new TreeMap<String, String>(); Map<File, Long> timestamps = new HashMap<File, Long>(); pathFilter = pathFilter != null ? pathFilter : PathFilter.ALL; try {/*from w w w. j av a2s. c o m*/ String destPath = null; FileInputStream fis = new FileInputStream(m_FilePath); BufferedInputStream bis = new BufferedInputStream(fis); ZipInputStream zis = new ZipInputStream(bis); ZipFile zf = new ZipFile(m_FilePath); ZipEntry ze = null; String zeName = null; try { while ((ze = zis.getNextEntry()) != null) { zeName = ze.getName(); String filePath = genPathFile(zeName); destPath = path + File.separator + filePath; File fo = new File(destPath); if (pathFilter.accept(pathPrefix != null ? pathPrefix + "/" + zeName : zeName)) { String loggedPath = fo.getAbsolutePath(); if (basePath != null) { loggedPath = StringUtils.substringAfter(loggedPath, basePath); } unzippedFiles.put(filePath, loggedPath); long lastModified = ze.getTime(); if (lastModified > 0) { timestamps.put(fo, lastModified); } if (ze.isDirectory()) { fo.mkdirs(); } else if (overwrite || !fo.exists()) { File parent = new File(fo.getParent()); parent.mkdirs(); FileOutputStream fos = new FileOutputStream(fo); copyStream(zis, fos); } } zis.closeEntry(); } } finally { // Important !!! zf.close(); fis.close(); zis.close(); bis.close(); } } catch (IOException ioe) { logger.error(" fail unzipping " + ioe.getMessage(), ioe); throw new JahiaException(CLASS_NAME, "faile processing unzip", JahiaException.SERVICE_ERROR, JahiaException.ERROR_SEVERITY, ioe); } // preserve last modified time stamps for (Map.Entry<File, Long> tst : timestamps.entrySet()) { try { tst.getKey().setLastModified(tst.getValue()); } catch (Exception e) { logger.warn("Unable to set last mofified date for file {}. Cause: {}", tst.getKey(), e.getMessage()); } } return unzippedFiles; }
From source file:nl.coinsweb.sdk.FileManager.java
/** * Extracts all the content of the .ccr-file specified in the constructor to [TEMP_ZIP_PATH] / [internalRef]. * *//*w w w. j ava2 s .c om*/ public static void unzipTo(File sourceFile, Path destinationPath) { byte[] buffer = new byte[1024]; String startFolder = null; try { // Get the zip file content ZipInputStream zis = new ZipInputStream(new FileInputStream(sourceFile)); ZipEntry ze = zis.getNextEntry(); while (ze != null) { if (ze.isDirectory()) { ze = zis.getNextEntry(); continue; } String fileName = ze.getName(); log.info("Dealing with file " + fileName); // If the first folder is a somename/bim/file.ref skip it Path filePath = Paths.get(fileName); Path pathPath = filePath.getParent(); if (pathPath.endsWith("bim") || pathPath.endsWith("bim/repository") || pathPath.endsWith("doc") || pathPath.endsWith("woa")) { Path pathRoot = pathPath.endsWith("repository") ? pathPath.getParent().getParent() : pathPath.getParent(); String prefix = ""; if (pathRoot != null) { prefix = pathRoot.toString(); } if (startFolder == null) { startFolder = prefix; log.debug("File root set to: " + startFolder); } else if (startFolder != null && !prefix.equals(startFolder)) { throw new InvalidContainerFileException( "The container file has an inconsistent file root, was " + startFolder + ", now dealing with " + prefix + "."); } } else { log.debug("Skipping file: " + filePath.toString()); continue; } String insideStartFolder = filePath.toString().substring(startFolder.length()); File newFile = new File(destinationPath + "/" + insideStartFolder); log.info("Extract " + newFile); // Create all non exists folders // else you will hit FileNotFoundException for compressed folder new File(newFile.getParent()).mkdirs(); FileOutputStream fos = new FileOutputStream(newFile); int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); ze = zis.getNextEntry(); } zis.closeEntry(); zis.close(); } catch (IOException ex) { ex.printStackTrace(); } }
From source file:org.jahia.utils.maven.plugin.DeployMojo.java
/** * Deploy WAR artifact to application server * @param dependencyNode/*from w w w .j a v a2 s.c o m*/ */ protected void deployWarDependency(DependencyNode dependencyNode) throws Exception { Artifact artifact = dependencyNode.getArtifact(); File webappDir = getWebappDeploymentDir(); getLog().info("Deploying artifact " + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getVersion() + "(file: " + artifact.getFile() + ")"); getLog().info("Updating " + artifact.getType() + " resources for " + getDeployer().getName() + " in directory " + webappDir); String[] excludes = getDeployer().getWarExcludes() != null ? StringUtils.split(getDeployer().getWarExcludes(), ",") : null; // if we are dealing with WAR overlay, we want to overwrite the target boolean overwrite = StringUtils.isNotEmpty(artifact.getClassifier()); try { ZipInputStream z = new ZipInputStream(new FileInputStream(artifact.getFile())); ZipEntry entry; int cnt = 0; while ((entry = z.getNextEntry()) != null) { if (!entry.isDirectory()) { if (excludes != null) { boolean doExclude = false; for (String excludePattern : excludes) { if (SelectorUtils.matchPath(excludePattern, entry.getName())) { doExclude = true; break; } } if (doExclude) { continue; } } File target = new File(webappDir, entry.getName()); if (overwrite || entry.getTime() > target.lastModified()) { target.getParentFile().mkdirs(); FileOutputStream fileOutputStream = new FileOutputStream(target); IOUtils.copy(z, fileOutputStream); fileOutputStream.close(); cnt++; } } else { //in the case of empty folders create anyway (new File(webappDir, entry.getName())).mkdir(); } } z.close(); getLog().info("Copied " + cnt + " files."); } catch (IOException e) { getLog().error("Error while deploying dependency", e); } }
From source file:ninja.command.PackageCommand.java
public void unzip(File zipFile, File outputFolder) { byte[] buffer = new byte[1024]; try {// ww w .j ava 2 s. c o m // create output directory is not exists File folder = outputFolder; if (!folder.exists()) { folder.mkdir(); } // get the zip file content ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile)); // get the zipped file list entry ZipEntry ze = zis.getNextEntry(); String zipFilename = zipFile.getName(); while (ze != null) { if (ze.isDirectory()) { ze = zis.getNextEntry(); continue; } String fileName = ze.getName(); File newFile = new File(outputFolder, fileName); String parentFolder = newFile.getParentFile().getName(); // (!"META-INF".equals(parentFolder)) if (newFile.exists() && !"about.html".equals(fileName) && !"META-INF/DEPENDENCIES".equals(fileName) && !"META-INF/LICENSE".equals(fileName) && !"META-INF/NOTICE".equals(fileName) && !"META-INF/NOTICE.txt".equals(fileName) && !"META-INF/MANIFEST.MF".equals(fileName) && !"META-INF/LICENSE.txt".equals(fileName) && !"META-INF/INDEX.LIST".equals(fileName)) { String conflicted = zipManifest.get(newFile.getAbsolutePath()); if (conflicted == null) conflicted = "unknown"; info(String.format("Conflicts for '%s' with '%s'. File alreay exists '%s", zipFilename, conflicted, newFile)); conflicts++; } else zipManifest.put(newFile.getAbsolutePath(), zipFile.getName()); // create all non exists folders // else you will hit FileNotFoundException for compressed folder new File(newFile.getParent()).mkdirs(); FileOutputStream fos = new FileOutputStream(newFile); int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); ze = zis.getNextEntry(); count++; } zis.closeEntry(); zis.close(); } catch (IOException ex) { ex.printStackTrace(); } }
From source file:au.org.ala.layers.dao.LayerIntersectDAOImpl.java
ArrayList<String> remoteSampling(IntersectionFile[] intersectionFiles, double[][] points, IntersectCallback callback) {/*from w w w . jav a 2s . c om*/ logger.info("begin REMOTE sampling, number of threads " + intersectConfig.getThreadCount() + ", number of layers=" + intersectionFiles.length + ", number of coordinates=" + points.length); ArrayList<String> output = null; try { long start = System.currentTimeMillis(); URL url = new URL(intersectConfig.getLayerIndexUrl() + "/intersect/batch"); URLConnection c = url.openConnection(); c.setDoOutput(true); OutputStreamWriter out = null; try { out = new OutputStreamWriter(c.getOutputStream()); out.write("fids="); for (int i = 0; i < intersectionFiles.length; i++) { if (i > 0) { out.write(","); } out.write(intersectionFiles[i].getFieldId()); } out.write("&points="); for (int i = 0; i < points.length; i++) { if (i > 0) { out.write(","); } out.write(String.valueOf(points[i][1])); out.write(","); out.write(String.valueOf(points[i][0])); } out.flush(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (out != null) { try { out.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } JSONObject jo = JSONObject.fromObject(IOUtils.toString(c.getInputStream())); String checkUrl = jo.getString("statusUrl"); //check status boolean notFinished = true; String downloadUrl = null; while (notFinished) { //wait 5s before querying status Thread.sleep(5000); jo = JSONObject.fromObject(IOUtils.toString(new URI(checkUrl).toURL().openStream())); if (jo.containsKey("error")) { notFinished = false; } else if (jo.containsKey("status")) { String status = jo.getString("status"); if ("finished".equals(status)) { downloadUrl = jo.getString("downloadUrl"); notFinished = false; } else if ("cancelled".equals(status) || "error".equals(status)) { notFinished = false; } } } ZipInputStream zis = null; CSVReader csv = null; InputStream is = null; ArrayList<StringBuilder> tmpOutput = new ArrayList<StringBuilder>(); long mid = System.currentTimeMillis(); try { is = new URI(downloadUrl).toURL().openStream(); zis = new ZipInputStream(is); ZipEntry ze = zis.getNextEntry(); csv = new CSVReader(new InputStreamReader(zis)); for (int i = 0; i < intersectionFiles.length; i++) { tmpOutput.add(new StringBuilder()); } String[] line; int row = 0; csv.readNext(); //discard header while ((line = csv.readNext()) != null) { //order is consistent with request for (int i = 2; i < line.length && i - 2 < tmpOutput.size(); i++) { if (row > 0) { tmpOutput.get(i - 2).append("\n"); } tmpOutput.get(i - 2).append(line[i]); } row++; } } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (zis != null) { try { zis.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } if (is != null) { try { is.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } if (csv != null) { try { csv.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } output = new ArrayList<String>(); for (int i = 0; i < tmpOutput.size(); i++) { output.add(tmpOutput.get(i).toString()); tmpOutput.set(i, null); } long end = System.currentTimeMillis(); logger.info("sample time for " + 5 + " layers and " + 3 + " coordinates: get response=" + (mid - start) + "ms, write response=" + (end - mid) + "ms"); } catch (Exception e) { logger.error(e.getMessage(), e); } return output; }
From source file:com.dibsyhex.apkdissector.ZipReader.java
public void getZipContents(String name) { try {//from w w w. ja v a 2 s. com File file = new File(name); FileInputStream fileInputStream = new FileInputStream(file); ZipInputStream zipInputStream = new ZipInputStream(fileInputStream); //System.out.println(zipInputStream.available()); //System.out.println("Reading each entries in details:"); ZipFile zipFile = new ZipFile(file); ZipEntry zipEntry; response.displayLog("Begining to extract"); while ((zipEntry = zipInputStream.getNextEntry()) != null) { String filename = "extracts" + File.separator + file.getName() + File.separator + zipEntry.getName(); System.out.println(filename); response.displayLog(filename); File extractDirectory = new File(filename); //Create the directories new File(extractDirectory.getParent()).mkdirs(); //Now write the contents InputStream inputStream = zipFile.getInputStream(zipEntry); OutputStream outputStream = new FileOutputStream(extractDirectory); FileUtils.copyInputStreamToFile(inputStream, extractDirectory); //Decode the xml files if (filename.endsWith(".xml")) { //First create a temp file at a location temp/extract/... File temp = new File("temp" + File.separator + extractDirectory); new File(temp.getParent()).mkdirs(); //Create an object of XML Decoder XmlDecoder xmlDecoder = new XmlDecoder(); InputStream inputStreamTemp = new FileInputStream(extractDirectory); byte[] buf = new byte[80000];//increase int bytesRead = inputStreamTemp.read(buf); String xml = xmlDecoder.decompressXML(buf); //System.out.println(xml); FileUtils.writeStringToFile(temp, xml); //Now rewrite the files at the original locations FileUtils.copyFile(temp, extractDirectory); } } response.displayLog("Extraction Done !"); System.out.println(" DONE ! "); zipInputStream.close(); } catch (Exception e) { System.out.println(e.toString()); response.displayError(e.toString()); } }
From source file:org.candlepin.sync.Importer.java
/** * Create a tar.gz archive of the exported directory. * * @param exportDir Directory where Candlepin data was exported. * @return File reference to the new archive tar.gz. *//* w w w .j av a 2 s . co m*/ private File extractArchive(File tempDir, File exportFile) throws IOException, ImportExtractionException { log.debug("Extracting archive to: " + tempDir.getAbsolutePath()); byte[] buf = new byte[1024]; ZipInputStream zipinputstream = null; try { zipinputstream = new ZipInputStream(new FileInputStream(exportFile)); ZipEntry zipentry = zipinputstream.getNextEntry(); if (zipentry == null) { throw new ImportExtractionException( i18n.tr("The archive {0} is not " + "a properly compressed file or is empty", exportFile.getName())); } while (zipentry != null) { //for each entry to be extracted String entryName = zipentry.getName(); if (log.isDebugEnabled()) { log.debug("entryname " + entryName); } File newFile = new File(entryName); String directory = newFile.getParent(); if (directory != null) { new File(tempDir, directory).mkdirs(); } FileOutputStream fileoutputstream = null; try { fileoutputstream = new FileOutputStream(new File(tempDir, entryName)); int n; while ((n = zipinputstream.read(buf, 0, 1024)) > -1) { fileoutputstream.write(buf, 0, n); } } finally { if (fileoutputstream != null) { fileoutputstream.close(); } } zipinputstream.closeEntry(); zipentry = zipinputstream.getNextEntry(); } } finally { if (zipinputstream != null) { zipinputstream.close(); } } return new File(tempDir.getAbsolutePath(), "export"); }