List of usage examples for java.util.zip ZipInputStream read
public int read(byte[] b, int off, int len) throws IOException
From source file:Main.java
public static void unZip(String path) { int count = -1; int index = -1; String savepath = ""; savepath = path.substring(0, path.lastIndexOf(".")); try {//from w w w. j av a 2 s . c om BufferedOutputStream bos = null; ZipEntry entry = null; FileInputStream fis = new FileInputStream(path); ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis)); while ((entry = zis.getNextEntry()) != null) { byte data[] = new byte[buffer]; String temp = entry.getName(); index = temp.lastIndexOf("/"); if (index > -1) temp = temp.substring(index + 1); String tempDir = savepath + "/zip/"; File dir = new File(tempDir); dir.mkdirs(); temp = tempDir + temp; File f = new File(temp); f.createNewFile(); FileOutputStream fos = new FileOutputStream(f); bos = new BufferedOutputStream(fos, buffer); while ((count = zis.read(data, 0, buffer)) != -1) { bos.write(data, 0, count); } bos.flush(); bos.close(); } zis.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:Main.java
/** * Extract a zip resource into real files and directories * /* w w w . j av a 2 s . c om*/ * @param in typically given as getResources().openRawResource(R.raw.something) * @param directory target directory * @param overwrite indicates whether to overwrite existing files * @return list of files that were unpacked (if overwrite is false, this list won't include files * that existed before) * @throws IOException */ public static List<File> extractZipResource(InputStream in, File directory, boolean overwrite) throws IOException { final int BUFSIZE = 2048; byte buffer[] = new byte[BUFSIZE]; ZipInputStream zin = new ZipInputStream(new BufferedInputStream(in, BUFSIZE)); List<File> files = new ArrayList<File>(); ZipEntry entry; directory.mkdirs(); while ((entry = zin.getNextEntry()) != null) { File file = new File(directory, entry.getName()); files.add(file); if (overwrite || !file.exists()) { if (entry.isDirectory()) { file.mkdirs(); } else { file.getParentFile().mkdirs(); // Necessary because some zip files lack directory entries. BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file), BUFSIZE); int nRead; while ((nRead = zin.read(buffer, 0, BUFSIZE)) > 0) { bos.write(buffer, 0, nRead); } bos.flush(); bos.close(); } } } zin.close(); return files; }
From source file:org.ancoron.osgi.test.glassfish.GlassfishHelper.java
public static void unzip(String zipFile, String targetPath) throws IOException { log.log(Level.INFO, "Extracting {0} ...", zipFile); log.log(Level.INFO, "...target directory: {0}", targetPath); File path = new File(targetPath); path.delete();//from ww w . j a v a 2s . c om path.mkdirs(); BufferedOutputStream dest = null; FileInputStream fis = new FileInputStream(zipFile); ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis)); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { if (entry.isDirectory()) { File f = new File(targetPath + "/" + entry.getName()); f.mkdirs(); continue; } int count; byte data[] = new byte[BUFFER]; // write the files to the disk FileOutputStream fos = new FileOutputStream(targetPath + "/" + entry.getName()); dest = new BufferedOutputStream(fos, BUFFER); while ((count = zis.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); } zis.close(); }
From source file:JarMaker.java
/** * @param f_name : source zip file path name * @param dir_name : target dir file path *//* w ww . jav a 2 s. c om*/ public static void unpackJar(String f_name, String dir_name) throws IOException { BufferedInputStream bism = new BufferedInputStream(new FileInputStream(f_name)); ZipInputStream zism = new ZipInputStream(bism); for (ZipEntry z = zism.getNextEntry(); z != null; z = zism.getNextEntry()) { File f = new File(dir_name, z.getName()); if (z.isDirectory()) { f.mkdirs(); } else { f.getParentFile().mkdirs(); BufferedOutputStream bosm = new BufferedOutputStream(new FileOutputStream(f)); int i; byte[] buffer = new byte[1024 * 512]; try { while ((i = zism.read(buffer, 0, buffer.length)) != -1) bosm.write(buffer, 0, i); } catch (IOException ie) { throw ie; } bosm.close(); } } zism.close(); bism.close(); }
From source file:org.bml.util.CompressUtils.java
/** * Extracts a zip | jar | war archive to the specified directory. * Uses the passed buffer size for read operations. * * @param zipFile/*from w ww . j a va 2 s.com*/ * @param destDir * @param bufferSize * @throws IOException If there is an issue with the archive file or the file system. * @throws NullPointerException if any of the arguments are null. * @throws IllegalArgumentException if any of the arguments do not pass the * preconditions other than null tests. NOTE: This exception wil not be thrown * if this classes CHECKED member is set to false * * @pre zipFile!=null * @pre zipFile.exists() * @pre zipFile.canRead() * @pre zipFile.getName().matches("(.*[zZ][iI][pP])|(.*[jJ][aA][rR])") * * @pre destDir!=null * @pre destDir.exists() * @pre destDir.isDirectory() * @pre destDir.canWrite() * * @pre bufferSize > 0 */ public static void unzipFilesToPath(final File zipFile, final File destDir, final int bufferSize) throws IOException, IllegalArgumentException, NullPointerException { //zipFilePath.toLowerCase().endsWith(zipFilePath) if (CHECKED) { final String userName = User.getSystemUserName();//use cahced if possible //zipFile Preconditions.checkNotNull(zipFile, "Can not unzip null zipFile"); Preconditions.checkArgument(zipFile.getName().matches(ZIP_MIME_PATTERN), "Zip File at %s does not match the extensions allowed by the regex %s", zipFile, ZIP_MIME_PATTERN); Preconditions.checkArgument(zipFile.exists(), "Can not unzip file at %s. It does not exist.", zipFile); Preconditions.checkArgument(zipFile.canRead(), "Can not extract archive with no read permissions. Check File permissions. USER=%s FILE=%s", System.getProperty("user.name"), zipFile); //destDir Preconditions.checkNotNull(destDir, "Can not extract zipFileName=%s to a null destination", zipFile); Preconditions.checkArgument(destDir.isDirectory(), "Can not extract zipFileName %s to a destination %s that is not a directory", zipFile, destDir); Preconditions.checkArgument(destDir.exists(), "Can not extract zipFileName %s to a non existant destination %s", zipFile, destDir); Preconditions.checkArgument(destDir.canWrite(), "Can not extract archive with no write permissions. Check File permissions. USER=%s FILE=%s", System.getProperty("user.name"), destDir); //bufferSize Preconditions.checkArgument(bufferSize > 0, "Can not extract archive %s to %s with a buffer size less than 1 size = %s", zipFile, destDir, bufferSize); } final FileInputStream fileInputStream = new FileInputStream(zipFile); final ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(fileInputStream)); final String destBasePath = destDir.getAbsolutePath() + PATH_SEP; try { ZipEntry zipEntry; BufferedOutputStream destBufferedOutputStream; int byteCount; byte[] data; while ((zipEntry = zipInputStream.getNextEntry()) != null) { destBufferedOutputStream = new BufferedOutputStream( new FileOutputStream(destBasePath + zipEntry.getName()), bufferSize); data = new byte[bufferSize]; while ((byteCount = zipInputStream.read(data, 0, bufferSize)) != -1) { destBufferedOutputStream.write(data, 0, byteCount); } destBufferedOutputStream.flush(); destBufferedOutputStream.close(); } fileInputStream.close(); zipInputStream.close(); } catch (IOException ioe) { if (LOG.isWarnEnabled()) { LOG.warn(String.format("IOException caught while unziping archive %s to %s", zipFile, destDir), ioe); } throw ioe; } finally { IOUtils.closeQuietly(fileInputStream); IOUtils.closeQuietly(zipInputStream); } }
From source file:anotadorderelacoes.model.UtilidadesPacotes.java
/** * Verifica se um dado arquivo um classificador e, se sim, qual . Faz * isso descompactando o arquivo e procurando pelo arquivo "meta.ars". * /* www . ja v a 2s .co m*/ * @param arquivo * * @return "invalido" se no um classificador, "svm" ou "j48" caso * contrrio. */ public static String verificarClassificador(File arquivo) { String classificador = "invalido"; try { ZipInputStream zis = new ZipInputStream(new FileInputStream(arquivo)); ZipEntry ze; byte[] buffer = new byte[4096]; while ((ze = zis.getNextEntry()) != null) { FileOutputStream fos = new FileOutputStream(ze.getName()); int numBytes; while ((numBytes = zis.read(buffer, 0, buffer.length)) != -1) fos.write(buffer, 0, numBytes); fos.close(); zis.closeEntry(); if (ze.getName().equals("meta.ars")) { BufferedReader br = new BufferedReader(new FileReader("meta.ars")); String linha; while ((linha = br.readLine()) != null) { String[] valores = linha.split(":"); if (valores[0].equals("classificador")) classificador = valores[1]; } br.close(); } new File(ze.getName()).delete(); } } catch (FileNotFoundException ex) { Logger.getLogger("ARS logger").log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger("ARS logger").log(Level.SEVERE, null, ex); } catch (NullPointerException ex) { //Logger.getLogger( "ARS logger" ).log( Level.SEVERE, null, ex ); return classificador; } return classificador; }
From source file:Main.java
public static void unCompress(String zipPath, String toPath) throws IOException { File zipfile = new File(zipPath); if (!zipfile.exists()) return;//from ww w .j av a 2 s . c om if (!toPath.endsWith("/")) toPath += "/"; File destFile = new File(toPath); if (!destFile.exists()) destFile.mkdirs(); ZipInputStream zis = new ZipInputStream(new FileInputStream(zipfile)); ZipEntry entry = null; try { while ((entry = zis.getNextEntry()) != null) { if (entry.isDirectory()) { File file = new File(toPath + entry.getName() + "/"); file.mkdirs(); } else { File file = new File(toPath + entry.getName()); if (!file.getParentFile().exists()) file.getParentFile().mkdirs(); FileOutputStream fos = null; try { fos = new FileOutputStream(file); byte buf[] = new byte[1024]; int len = -1; while ((len = zis.read(buf, 0, 1024)) != -1) { fos.write(buf, 0, len); } } finally { if (fos != null) { try { fos.close(); } catch (Exception e) { } } } } } } finally { zis.close(); } }
From source file:JarMaker.java
/** * Combine several jar files and some given files into one jar file. * @param outJar The output jar file's filename. * @param inJarsList The jar files to be combined * @param filter A filter that exclude some entries of input jars. User * should implement the EntryFilter interface. * @param inFileList The files to be added into the jar file. * @param prefixs The prefixs of files to be added into the jar file. * inFileList and prefixs should be paired. * @throws FileNotFoundException/*from w w w. j av a 2 s. com*/ * @throws IOException */ @SuppressWarnings("unchecked") public static void combineJars(String outJar, String[] inJarsList, EntryFilter filter, String[] inFileList, String[] prefixs) throws FileNotFoundException, IOException { JarOutputStream jout = new JarOutputStream(new FileOutputStream(outJar)); ArrayList entryList = new ArrayList(); for (int i = 0; i < inJarsList.length; i++) { BufferedInputStream bufferedinputstream = new BufferedInputStream(new FileInputStream(inJarsList[i])); ZipInputStream zipinputstream = new ZipInputStream(bufferedinputstream); byte abyte0[] = new byte[1024 * 4]; for (ZipEntry zipentry = zipinputstream.getNextEntry(); zipentry != null; zipentry = zipinputstream .getNextEntry()) { if (filter.accept(zipentry)) { if (!entryList.contains(zipentry.getName())) { jout.putNextEntry(zipentry); if (!zipentry.isDirectory()) { int j; try { while ((j = zipinputstream.read(abyte0, 0, abyte0.length)) != -1) jout.write(abyte0, 0, j); } catch (IOException ie) { throw ie; } } entryList.add(zipentry.getName()); } } } zipinputstream.close(); bufferedinputstream.close(); } for (int i = 0; i < inFileList.length; i++) { add(jout, new File(inFileList[i]), prefixs[i]); } jout.close(); }
From source file:mashapeautoloader.MashapeAutoloader.java
/** * @param libraryName//from w ww . j a v a2s. c o 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.glaf.core.entity.mybatis.MyBatisSessionFactory.java
public static Map<String, byte[]> getZipBytesMap(ZipInputStream zipInputStream) { Map<String, byte[]> zipMap = new java.util.HashMap<String, byte[]>(); java.util.zip.ZipEntry zipEntry = null; ByteArrayOutputStream baos = null; BufferedOutputStream bos = null; byte tmpByte[] = null; try {/*from ww w. j a v a2 s .c o m*/ while ((zipEntry = zipInputStream.getNextEntry()) != null) { String name = zipEntry.getName(); if (StringUtils.endsWith(name, "Mapper.xml")) { tmpByte = new byte[BUFFER]; baos = new ByteArrayOutputStream(); bos = new BufferedOutputStream(baos, BUFFER); int i = 0; while ((i = zipInputStream.read(tmpByte, 0, BUFFER)) != -1) { bos.write(tmpByte, 0, i); } bos.flush(); byte[] bytes = baos.toByteArray(); IOUtils.closeStream(baos); IOUtils.closeStream(baos); zipMap.put(zipEntry.getName(), bytes); } } } catch (Exception ex) { throw new RuntimeException(ex); } finally { IOUtils.closeStream(baos); IOUtils.closeStream(baos); } return zipMap; }