List of usage examples for java.util.zip ZipEntry getName
public String getName()
From source file:de.xwic.appkit.core.util.ZipUtil.java
/** * Unzips the files from the zipped file into the destination folder. * //from www . j a v a2 s .c om * @param zippedFile * the files array * @param destinationFolder * the folder in which the zip archive will be unzipped * @return the file array which consists into the files which were zipped in * the zippedFile * @throws IOException */ public static File[] unzip(File zippedFile, String destinationFolder) throws IOException { ZipFile zipFile = null; List<File> files = new ArrayList<File>(); try { zipFile = new ZipFile(zippedFile); Enumeration<?> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (!entry.isDirectory()) { String filePath = destinationFolder + System.getProperty("file.separator") + entry.getName(); FileOutputStream stream = new FileOutputStream(filePath); InputStream is = zipFile.getInputStream(entry); log.info("Unzipping " + entry.getName()); int n = 0; while ((n = is.read(BUFFER)) > 0) { stream.write(BUFFER, 0, n); } is.close(); stream.close(); files.add(new File(filePath)); } } zipFile.close(); } catch (IOException e) { log.error("Error: " + e.getMessage(), e); throw e; } finally { try { if (null != zipFile) { zipFile.close(); } } catch (IOException e) { log.error("Error: " + e.getMessage(), e); throw e; } } File[] array = files.toArray(new File[files.size()]); return array; }
From source file:com.aliyun.odps.local.common.utils.ArchiveUtils.java
/** * Given a File input it will unzip the file in a the unzip directory passed * as the second parameter// w ww. j av a 2 s .c o m * * @param inFile * The zip file as input * @param unzipDir * The unzip directory where to unzip the zip file. * @throws IOException */ public static void unZip(File inFile, File unzipDir) throws IOException { Enumeration<? extends ZipEntry> entries; ZipFile zipFile = new ZipFile(inFile); try { entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (!entry.isDirectory()) { InputStream in = zipFile.getInputStream(entry); try { File file = new File(unzipDir, entry.getName()); if (!file.getParentFile().mkdirs()) { if (!file.getParentFile().isDirectory()) { throw new IOException("Mkdirs failed to create " + file.getParentFile().toString()); } } OutputStream out = new FileOutputStream(file); try { byte[] buffer = new byte[8192]; int i; while ((i = in.read(buffer)) != -1) { out.write(buffer, 0, i); } } finally { out.close(); } } finally { in.close(); } } } } finally { zipFile.close(); } }
From source file:com.bukanir.android.utils.Utils.java
public static String unzipSubtitle(String zip, String path) { InputStream is;/*from w ww . jav a2 s .c om*/ ZipInputStream zis; try { String filename = null; is = new FileInputStream(zip); zis = new ZipInputStream(new BufferedInputStream(is)); ZipEntry ze; byte[] buffer = new byte[1024]; int count; while ((ze = zis.getNextEntry()) != null) { filename = ze.getName(); if (ze.isDirectory()) { File fmd = new File(path + "/" + filename); fmd.mkdirs(); continue; } if (filename.endsWith(".srt") || filename.endsWith(".sub")) { FileOutputStream fout = new FileOutputStream(path + "/" + filename); while ((count = zis.read(buffer)) != -1) { fout.write(buffer, 0, count); } fout.close(); zis.closeEntry(); break; } zis.closeEntry(); } zis.close(); File z = new File(zip); z.delete(); return path + "/" + filename; } catch (IOException e) { e.printStackTrace(); return null; } }
From source file:com.android.build.gradle.internal.transforms.ExtractJarsTransform.java
private static void extractJar(@NonNull File outJarFolder, @NonNull File jarFile, boolean extractCode) throws IOException { mkdirs(outJarFolder);//from www .j av a 2s.c om HashSet<String> lowerCaseNames = new HashSet<>(); boolean foundCaseInsensitiveIssue = false; try (Closer closer = Closer.create()) { FileInputStream fis = closer.register(new FileInputStream(jarFile)); ZipInputStream zis = closer.register(new ZipInputStream(fis)); // loop on the entries of the intermediary package and put them in the final package. ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { try { String name = entry.getName(); // do not take directories if (entry.isDirectory()) { continue; } foundCaseInsensitiveIssue = foundCaseInsensitiveIssue || !lowerCaseNames.add(name.toLowerCase(Locale.US)); Action action = getAction(name, extractCode); if (action == Action.COPY) { File outputFile = new File(outJarFolder, name.replace('/', File.separatorChar)); mkdirs(outputFile.getParentFile()); try (Closer closer2 = Closer.create()) { java.io.OutputStream outputStream = closer2 .register(new BufferedOutputStream(new FileOutputStream(outputFile))); ByteStreams.copy(zis, outputStream); outputStream.flush(); } } } finally { zis.closeEntry(); } } } if (foundCaseInsensitiveIssue) { LOGGER.error( "Jar '{}' contains multiple entries which will map to " + "the same file on case insensitive file systems.\n" + "This can be caused by obfuscation with useMixedCaseClassNames.\n" + "This build will be incorrect on case insensitive " + "file systems.", jarFile.getAbsolutePath()); } }
From source file:com.idocbox.common.file.ZipExtracter.java
/** * Is given zip entry under given directory? * @param zipEntry zip entry// w w w. java 2 s .c o m * @param dir directory in zip file, it is end with "/". * use "/" to represent root of zip file. * For example, conf/ represents subdirectory in zip file. * @return true: the entry is under the directory. * false:the entry is not under the directory. */ private static boolean isUnderDir(final ZipEntry zipEntry, final String dir) { boolean isunder = false; if ("/".equals(dir)) {//dir is root of zip file. return true; } if (null != zipEntry) { String name = zipEntry.getName(); int idx = name.lastIndexOf('/'); if (idx > 0) {//the entry is under sub directory of zip file. String subDir = name.substring(0, idx + 1); if (subDir.startsWith(dir)) { isunder = true; } else { isunder = false; } } else {//the entry is under root directory, but dir is not root. isunder = false; } } return isunder; }
From source file:com.ccoe.build.utils.CompressUtils.java
/** * Uncompress a zip to files// w w w. j a v a 2 s . c o m * @param zip * @param unzipdir * @param isNeedClean * @return * @throws FileNotFoundException * @throws IOException */ public static List<File> unCompress(File zip, String unzipdir) throws IOException { ArrayList<File> unzipfiles = new ArrayList<File>(); FileInputStream fi = new FileInputStream(zip); ZipInputStream zi = new ZipInputStream(new BufferedInputStream(fi)); try { ZipEntry entry; while ((entry = zi.getNextEntry()) != null) { System.out.println("Extracting: " + entry); int count; byte data[] = new byte[BUFFER]; File unzipfile = new File(unzipdir + File.separator + entry.getName()); FileOutputStream fos = new FileOutputStream(unzipfile); BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER); while ((count = zi.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); unzipfiles.add(unzipfile); } } catch (IOException e) { throw e; } finally { IOUtils.closeQuietly(zi); } return unzipfiles; }
From source file:net.sourceforge.dita4publishers.tools.dxp.DitaDxpHelper.java
/** * @param zipFile// ww w.ja va2 s. c om * @param dxpOptions * @return * @throws DitaDxpException */ public static ZipEntry getDxpPackageRootMap(ZipFile zipFile, MapBosProcessorOptions dxpOptions) throws DitaDxpException { List<ZipEntry> candidateRootEntries = new ArrayList<ZipEntry>(); List<ZipEntry> candidateDirs = new ArrayList<ZipEntry>(); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); File temp = new File(entry.getName()); String parentPath = temp.getParent(); if (entry.isDirectory()) { if (parentPath == null || "".equals(parentPath)) { candidateDirs.add(entry); } } else { if (entry.getName().equals("dita_dxp_manifest.ditamap")) { return entry; } if (entry.getName().endsWith(".ditamap")) { if (parentPath == null || "".equals(parentPath)) { candidateRootEntries.add(entry); } } } } // If we get here then we didn't find a manifest map, so look for // root map. // If exactly one map at the top level, must be the root map of the package. if (candidateRootEntries.size() == 1) { if (!dxpOptions.isQuiet()) log.info("Using root map " + candidateRootEntries.get(0).getName()); return candidateRootEntries.get(0); } // If there is more than one top-level dir, thank you for playing: if (candidateRootEntries.size() == 0 & candidateDirs.size() > 1) { throw new DitaDxpException( "No manifest map, no map in root of package, and more than one top-level directory in package."); } // If there is exactly one root directory, look in it for exactly one map: if (candidateDirs.size() == 1) { String parentPath = candidateDirs.get(0).getName(); entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); File temp = new File(entry.getName()); String entryParent = temp.getParent(); if (entryParent == null) entryParent = "/"; else entryParent += "/"; if (parentPath.equals(entryParent) && entry.getName().endsWith(".ditamap")) { candidateRootEntries.add(entry); } } if (candidateRootEntries.size() == 1) { // Must be the root map if (!dxpOptions.isQuiet()) log.info("Using root map " + candidateRootEntries.get(0).getName()); return candidateRootEntries.get(0); } if (candidateRootEntries.size() > 1) { throw new DitaDxpException( "No manifest map and found more than one map in the root directory of the package."); } } // Should never get here: throw new DitaDxpException("Unable to find package manifest map or single root map in DXP package."); }
From source file:edu.kit.dama.util.ZipUtils.java
/** * Extract single entry of zip file./*w ww. jav a 2s .co m*/ * * @param pOutputDir where to store the unzipped entry. * @param pZipFile file containing zipped files. * @param pEntry one entry to extract. * @throws IOException missing access rights? */ private static void extractEntry(File pOutputDir, ZipFile pZipFile, ZipEntry pEntry) throws IOException { File destinationFilePath = new File(pOutputDir, pEntry.getName()); if (pEntry.isDirectory()) { // The following command is neccessary to create also // empty directories. if (destinationFilePath.mkdirs()) { LOGGER.trace("create directory: '{}'", destinationFilePath.getPath()); } } else { //create directories if required. if (destinationFilePath.getParentFile().mkdirs()) { LOGGER.trace("create directory: '{}'", destinationFilePath.getPath()); } } //if the entry is directory, leave it. Otherwise extract it. if (!pEntry.isDirectory()) { LOGGER.debug("Extracting " + destinationFilePath); /* * Get the InputStream for current entry * of the zip file using * * InputStream getInputStream(Entry entry) method. */ int noOfBytes; byte buffer[] = new byte[1024]; try (BufferedInputStream bis = new BufferedInputStream(pZipFile.getInputStream(pEntry)); FileOutputStream fos = new FileOutputStream(destinationFilePath); BufferedOutputStream bos = new BufferedOutputStream(fos, buffer.length);) { /* * read the current entry from the zip file, extract it * and write the extracted file. */ while ((noOfBytes = bis.read(buffer, 0, buffer.length)) != -1) { bos.write(buffer, 0, noOfBytes); } //flush the output stream. bos.flush(); } } }
From source file:mashapeautoloader.MashapeAutoloader.java
/** * @param libraryName/*from w w w . ja v a 2 s.co m*/ * * Returns false if something wrong, otherwise true (API interface * already exists or just well downloaded) */ private static boolean downloadLib(String libraryName) { URL url; URLConnection urlConn; // check (or make) for apiStore directory File apiStoreDir = new File(apiStore); if (!apiStoreDir.isDirectory()) apiStoreDir.mkdir(); String javaFilePath = apiStore + libraryName + ".java"; File javaFile = new File(javaFilePath); // check if the API interface exists if (javaFile.exists()) return true; try { // download the API interface's archive url = new URL(MASHAPE_DOWNLOAD_ROOT + libraryName); urlConn = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) urlConn; httpConn.setInstanceFollowRedirects(false); urlConn.setDoInput(true); urlConn.setDoOutput(false); urlConn.setUseCaches(false); // extract the archive stream ZipInputStream zip = new ZipInputStream(urlConn.getInputStream()); String expectedEntryName = libraryName + ".java"; while (true) { ZipEntry nextEntry = zip.getNextEntry(); if (nextEntry == null) return false; String name = nextEntry.getName(); if (name.equals(expectedEntryName)) { // save .java locally FileOutputStream javaFileStream = new FileOutputStream(javaFilePath); byte[] buf = new byte[1024]; int n; while ((n = zip.read(buf, 0, 1024)) > -1) javaFileStream.write(buf, 0, n); // compile it into .class file JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); int result = compiler.run(null, null, null, javaFilePath); System.out.println(result); return result == 0; } } } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:com.sencko.basketball.stats.advanced.FIBAJsonParser.java
private static void addToCache(String cacheName, Game game) throws FileNotFoundException, UnsupportedEncodingException, IOException { logger.log(Level.FINEST, "Saving file {0} to cache", cacheName); File file = new File("archive.zip"); File file1 = null;/*w w w .j a va2 s . co m*/ if (file.exists()) { //copy to archive1, return file1 = new File("archive1.zip"); if (file1.exists()) { if (!file1.delete()) { logger.log(Level.WARNING, "Unable to delete file {0}", file1.getCanonicalPath()); return; } } if (!file.renameTo(file1)) { logger.log(Level.WARNING, "Unable to rename file {0} to {1}", new Object[] { file.getCanonicalPath(), file1.getCanonicalPath() }); // unable to move to archive1 and whole operation fails!!! return; } } try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file))) { out.setLevel(9); // name the file inside the zip file out.putNextEntry(new ZipEntry(cacheName)); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(out, "UTF-8"); JsonWriter jsonWriter = new JsonWriter(outputStreamWriter); jsonWriter.setIndent(" "); builder.create().toJson(game, Game.class, jsonWriter); jsonWriter.flush(); if (file1 != null) { try (ZipFile zipFile = new ZipFile(file1)) { Enumeration<? extends ZipEntry> files = zipFile.entries(); while (files.hasMoreElements()) { ZipEntry entry = files.nextElement(); try (InputStream in = zipFile.getInputStream(entry)) { out.putNextEntry(new ZipEntry(entry.getName())); IOUtils.copy(in, out); } } } file1.delete(); } } }