List of usage examples for java.util.zip ZipFile OPEN_READ
int OPEN_READ
To view the source code for java.util.zip ZipFile OPEN_READ.
Click Source Link
From source file:com.aurel.track.lucene.util.FileUtil.java
public static void unzipFile(File uploadZip, File unzipDestinationDirectory) throws IOException { if (!unzipDestinationDirectory.exists()) { unzipDestinationDirectory.mkdirs(); }//ww w .j a v a2 s .co m final int BUFFER = 2048; // Open Zip file for reading ZipFile zipFile = new ZipFile(uploadZip, 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(); 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 = 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); BufferedOutputStream 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); } dest.flush(); dest.close(); is.close(); } } zipFile.close(); }
From source file:org.esa.s1tbx.sentinel1.gpf.EAPPhaseCorrectionOp.java
private void readAuxCalFile() throws Exception { try {//from w ww .j av a 2 s .com final DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance(); final DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder(); final Document doc; if (auxCalFile.getName().toLowerCase().endsWith(".zip")) { final ZipFile productZip = new ZipFile(auxCalFile, ZipFile.OPEN_READ); final Enumeration<? extends ZipEntry> entries = productZip.entries(); final ZipEntry folderEntry = entries.nextElement(); final ZipEntry zipEntry = productZip.getEntry(folderEntry.getName() + "data/s1a-aux-cal.xml"); InputStream is = productZip.getInputStream(zipEntry); doc = documentBuilder.parse(is); } else { doc = documentBuilder.parse(auxCalFile); } if (doc == null) { System.out.println("EAPPhaseCorrection: failed to create Document for AUX_CAL file"); return; } doc.getDocumentElement().normalize(); final org.w3c.dom.Node calibrationParamsListNode = doc.getElementsByTagName("auxiliaryCalibration") .item(0).getChildNodes().item(1); org.w3c.dom.Node childNode = calibrationParamsListNode.getFirstChild(); while (childNode != null) { if (childNode.getNodeName().equals("calibrationParams")) { final String swath = getNodeTextContent(childNode, "swath"); if (swath != null && swath.contains(acquisitionMode)) { final String pol = getNodeTextContent(childNode, "polarisation"); readOneEAPVector(childNode, swath, pol.toUpperCase()); } } childNode = childNode.getNextSibling(); } } catch (IOException e) { System.out.println("EAPPhaseCorrection: IOException " + e.getMessage()); } catch (ParserConfigurationException e) { System.out.println("EAPPhaseCorrection: ParserConfigurationException " + e.getMessage()); } catch (SAXException e) { System.out.println("EAPPhaseCorrection: SAXException " + e.getMessage()); } catch (Exception e) { System.out.println("EAPPhaseCorrection: Exception " + e.getMessage()); } }
From source file:com.aurel.track.admin.server.dbbackup.DatabaseBackupBL.java
public static Properties getBackupInfo(File backupFile) throws DatabaseBackupBLException { Properties prop = new Properties(); ZipFile zipFile = null;// w w w .j ava2 s.c o m try { zipFile = new ZipFile(backupFile, ZipFile.OPEN_READ); } catch (IOException e) { throw new DatabaseBackupBLException(e.getMessage(), e); } ZipEntry zipEntryInfo = zipFile.getEntry(DataReader.FILE_NAME_INFO); if (zipEntryInfo == null) { try { zipFile.close(); } catch (IOException e) { throw new DatabaseBackupBLException(e.getMessage(), e); } throw new DatabaseBackupBLException("Invalid backup. No file info"); } try { prop.load(zipFile.getInputStream(zipEntryInfo)); } catch (IOException e) { throw new DatabaseBackupBLException(e.getMessage(), e); } try { zipFile.close(); } catch (IOException e) { throw new DatabaseBackupBLException(e.getMessage(), e); } return prop; }
From source file:com.hichinaschool.flashcards.libanki.Media.java
/** * Extract zip data./*from ww w . j a v a2s . c o m*/ * * @param zipData An input stream that represents a zipped file. * @return True if finished. */ public boolean syncAdd(File zipData) { boolean finished = false; ZipFile z = null; ArrayList<Object[]> media = new ArrayList<Object[]>(); long sizecnt = 0; JSONObject meta = null; int nextUsn = 0; try { z = new ZipFile(zipData, ZipFile.OPEN_READ); // get meta info first ZipEntry metaEntry = z.getEntry("_meta"); // if (metaEntry.getSize() >= 100000) { // Log.e(AnkiDroidApp.TAG, "Size for _meta entry found too big (" + z.getEntry("_meta").getSize() + ")"); // return false; // } meta = new JSONObject(Utils.convertStreamToString(z.getInputStream(metaEntry))); ZipEntry usnEntry = z.getEntry("_usn"); String usnstr = Utils.convertStreamToString(z.getInputStream(usnEntry)); nextUsn = Integer.parseInt(usnstr); } catch (JSONException e) { throw new RuntimeException(e); } catch (ZipException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } // Then loop through all files for (ZipEntry zentry : Collections.list(z.entries())) { // Check for zip bombs sizecnt += zentry.getSize(); if (sizecnt > 100 * 1024 * 1024) { Log.e(AnkiDroidApp.TAG, "Media zip file exceeds 100MB uncompressed, aborting unzipping"); return false; } if (zentry.getName().compareTo("_meta") == 0 || zentry.getName().compareTo("_usn") == 0) { // Ignore previously retrieved meta continue; } else if (zentry.getName().compareTo("_finished") == 0) { finished = true; } else { String name = meta.optString(zentry.getName()); if (illegal(name)) { continue; } String path = getDir().concat(File.separator).concat(name); try { Utils.writeToFile(z.getInputStream(zentry), path); } catch (IOException e) { throw new RuntimeException(e); } String csum = Utils.fileChecksum(path); // append db media.add(new Object[] { name, csum, _mtime(name) }); mMediaDb.execute("delete from log where fname = ?", new String[] { name }); } } // update media db and note new starting usn if (!media.isEmpty()) { mMediaDb.executeMany("insert or replace into media values (?,?,?)", media); } setUsn(nextUsn); // commits // if we have finished adding, we need to record the new folder mtime // so that we don't trigger a needless scan if (finished) { syncMod(); } return finished; }
From source file:com.blazemeter.bamboo.plugin.ServiceManager.java
public static void unzip(String srcZipFileName, String destDirectoryName, BuildLogger logger) { try {//from w w w . java 2 s. c o m BufferedInputStream bufIS = null; // create the destination directory structure (if needed) File destDirectory = new File(destDirectoryName); destDirectory.mkdirs(); // open archive for reading File file = new File(srcZipFileName); ZipFile zipFile = new ZipFile(file, ZipFile.OPEN_READ); //for every zip archive entry do Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries(); while (zipFileEntries.hasMoreElements()) { ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); logger.addBuildLogEntry("\tExtracting jtl report: " + entry); //create destination file File destFile = new File(destDirectory, entry.getName()); //create parent directories if needed File parentDestFile = destFile.getParentFile(); parentDestFile.mkdirs(); bufIS = new BufferedInputStream(zipFile.getInputStream(entry)); int currentByte; // buffer for writing file byte data[] = new byte[BUFFER_SIZE]; // write the current file to disk FileOutputStream fOS = new FileOutputStream(destFile); BufferedOutputStream bufOS = new BufferedOutputStream(fOS, BUFFER_SIZE); while ((currentByte = bufIS.read(data, 0, BUFFER_SIZE)) != -1) { bufOS.write(data, 0, currentByte); } // close BufferedOutputStream bufOS.flush(); bufOS.close(); } bufIS.close(); } catch (Exception e) { logger.addErrorLogEntry("Failed to unzip report: check that it is downloaded"); } }
From source file:org.opendatakit.survey.android.tasks.DownloadFormsTask.java
private String explodeZips(FormDetails fd, File tempMediaPath, int count, int total) { String message = ""; File[] zips = tempMediaPath.listFiles(new FileFilter() { @Override//from w ww . j a va 2 s . c o m public boolean accept(File pathname) { String name = pathname.getName(); return pathname.isFile() && name.substring(name.lastIndexOf('.') + 1).equals("zip"); } }); int zipCount = 0; for (File zipfile : zips) { ZipFile f = null; zipCount++; try { f = new ZipFile(zipfile, ZipFile.OPEN_READ); Enumeration<? extends ZipEntry> entries = f.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); File tempFile = new File(tempMediaPath, entry.getName()); String formattedString = appContext.getString(R.string.form_download_unzipping, fd.formID, zipfile.getName(), Integer.valueOf(zipCount).toString(), Integer.valueOf(zips.length).toString(), entry.getName()); publishProgress(formattedString, Integer.valueOf(count).toString(), Integer.valueOf(total).toString()); if (entry.isDirectory()) { tempFile.mkdirs(); } else { tempFile.getParentFile().mkdirs(); int bufferSize = 8192; InputStream in = new BufferedInputStream(f.getInputStream(entry), bufferSize); OutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile, false), bufferSize); // this is slow in the debugger.... int value; while ((value = in.read()) != -1) { out.write(value); } out.flush(); out.close(); in.close(); } WebLogger.getLogger(appName).i(t, "Extracted ZipEntry: " + entry.getName()); } } catch (IOException e) { WebLogger.getLogger(appName).printStackTrace(e); if (e.getCause() != null) { message += e.getCause().getMessage(); } else { message += e.getMessage(); } } finally { if (f != null) { try { f.close(); } catch (IOException e) { WebLogger.getLogger(appName).printStackTrace(e); WebLogger.getLogger(appName).e(t, "Closing of ZipFile failed: " + e.toString()); } } } } return (message.equals("") ? null : message); }
From source file:org.python.pydev.core.REF.java
/** * @param f the zip file that should be opened * @param pathInZip the path within the zip file that should be gotten * @param returnType the class that specifies the return type of this method. * If null, it'll return in the fastest possible way available. * Valid options are://from w w w. j av a 2 s . co m * String.class * IDocument.class * FastStringBuffer.class * * @return an object with the contents from a path within a zip file, having the return type * of the object specified by the parameter returnType. */ public static Object getCustomReturnFromZip(File f, String pathInZip, Class<? extends Object> returnType) throws Exception { ZipFile zipFile = new ZipFile(f, ZipFile.OPEN_READ); try { InputStream inputStream = zipFile.getInputStream(zipFile.getEntry(pathInZip)); try { return REF.getStreamContents(inputStream, null, null, returnType); } finally { inputStream.close(); } } finally { zipFile.close(); } }
From source file:org.zilverline.service.CollectionManagerImpl.java
/** * unZips a given zip file into cache directory with derived name. e.g. c:\temp\file.zip wil be unziiped into * [cacheDir]\file_zip\./*from w ww . j a v a 2 s. com*/ * * @param sourceZipFile the ZIP file to be unzipped * @param thisCollection the collection whose cache and contenDir is used * * @return File (new) directory containing zip file */ public static File unZip(final File sourceZipFile, final FileSystemCollection thisCollection) { // specify buffer size for extraction final int aBUFFER = 2048; File unzipDestinationDirectory = null; ZipFile zipFile = null; FileOutputStream fos = null; BufferedOutputStream dest = null; BufferedInputStream bis = null; try { // Specify destination where file will be unzipped unzipDestinationDirectory = file2CacheDir(sourceZipFile, thisCollection); log.info("unzipping " + sourceZipFile + " into " + unzipDestinationDirectory); // Open Zip file for reading zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ); // Create an enumeration of the entries in the zip file Enumeration zipFileEntries = zipFile.entries(); while (zipFileEntries.hasMoreElements()) { // grab a zip file entry ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); String currentEntry = entry.getName(); log.debug("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()) { bis = new BufferedInputStream(zipFile.getInputStream(entry)); int currentByte; // establish buffer for writing file byte[] data = new byte[aBUFFER]; // write the current file to disk fos = new FileOutputStream(destFile); dest = new BufferedOutputStream(fos, aBUFFER); // read and write until last byte is encountered while ((currentByte = bis.read(data, 0, aBUFFER)) != -1) { dest.write(data, 0, currentByte); } dest.flush(); dest.close(); bis.close(); } } zipFile.close(); // delete the zip file if it is in the cache, we don't need to store // it, since we've extracted the contents if (FileUtils.isIn(sourceZipFile, thisCollection.getCacheDirWithManagerDefaults())) { sourceZipFile.delete(); } } catch (Exception e) { log.error("Can't unzip: " + sourceZipFile, e); } finally { try { if (fos != null) { fos.close(); } if (dest != null) { dest.close(); } if (bis != null) { bis.close(); } } catch (IOException e1) { log.error("Error closing files", e1); } } return unzipDestinationDirectory; }
From source file:com.ichi2.async.DeckTask.java
private TaskData doInBackgroundImportReplace(TaskData... params) { Timber.d("doInBackgroundImportReplace"); Collection col = CollectionHelper.getInstance().getCol(mContext); String path = params[0].getString(); Resources res = AnkiDroidApp.getInstance().getBaseContext().getResources(); // extract the deck from the zip file String colPath = col.getPath(); File dir = new File(new File(colPath).getParentFile(), "tmpzip"); if (dir.exists()) { BackupManager.removeDir(dir);// www . j a va2 s . co m } publishProgress(new TaskData(res.getString(R.string.import_unpacking))); // from anki2.py String colFile = new File(dir, "collection.anki2").getAbsolutePath(); ZipFile zip; try { zip = new ZipFile(new File(path), ZipFile.OPEN_READ); } catch (IOException e) { Timber.e(e, "doInBackgroundImportReplace - Error while unzipping"); AnkiDroidApp.sendExceptionReport(e, "doInBackgroundImportReplace0"); return new TaskData(false); } if (!Utils.unzipFiles(zip, dir.getAbsolutePath(), new String[] { "collection.anki2", "media" }, null) || !(new File(colFile)).exists()) { return new TaskData(-2, null, false); } Collection tmpCol = null; try { tmpCol = Storage.Collection(colFile); if (!tmpCol.validCollection()) { tmpCol.close(); return new TaskData(-2, null, false); } } catch (Exception e) { Timber.e("Error opening new collection file... probably it's invalid"); try { tmpCol.close(); } catch (Exception e2) { // do nothing } return new TaskData(-2, null, false); } finally { if (tmpCol != null) { tmpCol.close(); } } publishProgress(new TaskData(res.getString(R.string.importing_collection))); if (col != null) { // unload collection and trigger a backup CollectionHelper.getInstance().closeCollection(true); CollectionHelper.getInstance().lockCollection(); BackupManager.performBackupInBackground(colPath, true); } // overwrite collection File f = new File(colFile); if (!f.renameTo(new File(colPath))) { // Exit early if this didn't work return new TaskData(-2, null, false); } int addedCount = -1; try { col = CollectionHelper.getInstance().reopenCollection(); CollectionHelper.getInstance().unlockCollection(); // because users don't have a backup of media, it's safer to import new // data and rely on them running a media db check to get rid of any // unwanted media. in the future we might also want to duplicate this step // import media HashMap<String, String> nameToNum = new HashMap<String, String>(); HashMap<String, String> numToName = new HashMap<String, String>(); File mediaMapFile = new File(dir.getAbsolutePath(), "media"); if (mediaMapFile.exists()) { JsonReader jr = new JsonReader(new FileReader(mediaMapFile)); jr.beginObject(); String name; String num; while (jr.hasNext()) { num = jr.nextName(); name = jr.nextString(); nameToNum.put(name, num); numToName.put(num, name); } jr.endObject(); jr.close(); } String mediaDir = col.getMedia().dir(); int total = nameToNum.size(); int i = 0; for (Map.Entry<String, String> entry : nameToNum.entrySet()) { String file = entry.getKey(); String c = entry.getValue(); File of = new File(mediaDir, file); if (!of.exists()) { Utils.unzipFiles(zip, mediaDir, new String[] { c }, numToName); } ++i; publishProgress(new TaskData(res.getString(R.string.import_media_count, (i + 1) * 100 / total))); } zip.close(); // delete tmp dir BackupManager.removeDir(dir); return new TaskData(true); } catch (RuntimeException e) { Timber.e(e, "doInBackgroundImportReplace - RuntimeException"); AnkiDroidApp.sendExceptionReport(e, "doInBackgroundImportReplace1"); return new TaskData(false); } catch (FileNotFoundException e) { Timber.e(e, "doInBackgroundImportReplace - FileNotFoundException"); AnkiDroidApp.sendExceptionReport(e, "doInBackgroundImportReplace2"); return new TaskData(false); } catch (IOException e) { Timber.e(e, "doInBackgroundImportReplace - IOException"); AnkiDroidApp.sendExceptionReport(e, "doInBackgroundImportReplace3"); return new TaskData(false); } }
From source file:com.hichinaschool.flashcards.async.DeckTask.java
private TaskData doInBackgroundImportReplace(TaskData... params) { // Log.i(AnkiDroidApp.TAG, "doInBackgroundImportReplace"); Collection col = params[0].getCollection(); String path = params[0].getString(); Resources res = AnkiDroidApp.getInstance().getBaseContext().getResources(); // extract the deck from the zip file String fileDir = AnkiDroidApp.getCurrentAnkiDroidDirectory() + "/tmpzip"; File dir = new File(fileDir); if (dir.exists()) { BackupManager.removeDir(dir);/*from w w w .java 2 s . co m*/ } publishProgress(new TaskData(res.getString(R.string.import_unpacking))); // from anki2.py String colFile = fileDir + "/collection.anki2"; ZipFile zip; try { zip = new ZipFile(new File(path), ZipFile.OPEN_READ); } catch (IOException e) { Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - Error while unzipping: ", e); AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportReplace0"); return new TaskData(false); } if (!Utils.unzipFiles(zip, fileDir, new String[] { "collection.anki2", "media" }, null) || !(new File(colFile)).exists()) { return new TaskData(-2, null, false); } Collection tmpCol = null; try { tmpCol = Storage.Collection(colFile); if (!tmpCol.validCollection()) { tmpCol.close(); return new TaskData(-2, null, false); } } finally { if (tmpCol != null) { tmpCol.close(); } } publishProgress(new TaskData(res.getString(R.string.importing_collection))); String colPath; if (col != null) { // unload collection and trigger a backup colPath = col.getPath(); AnkiDroidApp.closeCollection(true); BackupManager.performBackup(colPath, true); } // overwrite collection colPath = AnkiDroidApp.getCollectionPath(); File f = new File(colFile); f.renameTo(new File(colPath)); int addedCount = -1; try { col = AnkiDroidApp.openCollection(colPath); // because users don't have a backup of media, it's safer to import new // data and rely on them running a media db check to get rid of any // unwanted media. in the future we might also want to duplicate this step // import media HashMap<String, String> nameToNum = new HashMap<String, String>(); HashMap<String, String> numToName = new HashMap<String, String>(); File mediaMapFile = new File(fileDir, "media"); if (mediaMapFile.exists()) { JsonReader jr = new JsonReader(new FileReader(mediaMapFile)); jr.beginObject(); String name; String num; while (jr.hasNext()) { num = jr.nextName(); name = jr.nextString(); nameToNum.put(name, num); numToName.put(num, name); } jr.endObject(); jr.close(); } String mediaDir = col.getMedia().getDir(); int total = nameToNum.size(); int i = 0; for (Map.Entry<String, String> entry : nameToNum.entrySet()) { String file = entry.getKey(); String c = entry.getValue(); File of = new File(mediaDir, file); if (!of.exists()) { Utils.unzipFiles(zip, mediaDir, new String[] { c }, numToName); } ++i; publishProgress(new TaskData(res.getString(R.string.import_media_count, (i + 1) * 100 / total))); } zip.close(); // delete tmp dir BackupManager.removeDir(dir); publishProgress(new TaskData(res.getString(R.string.import_update_counts))); // Update the counts DeckTask.TaskData result = doInBackgroundLoadDeckCounts(new TaskData(col)); if (result == null) { return null; } return new TaskData(addedCount, result.getObjArray(), true); } catch (RuntimeException e) { Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - RuntimeException: ", e); AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportReplace1"); return new TaskData(false); } catch (FileNotFoundException e) { Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - FileNotFoundException: ", e); AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportReplace2"); return new TaskData(false); } catch (IOException e) { Log.e(AnkiDroidApp.TAG, "doInBackgroundImportReplace - IOException: ", e); AnkiDroidApp.saveExceptionReportFile(e, "doInBackgroundImportReplace3"); return new TaskData(false); } }