private int extractZipEntry(String out_path, ZipInputStream zip, int total_size, String mes) { BufferedOutputStream out = null; try { out = new BufferedOutputStream(new FileOutputStream(out_path)); } catch (Exception e) { sendMessage(-2, 0, "Failed to create file: " + e.toString()); return -1; } ; int total_read = 0; try { int len = zip.read(buf); while (len >= 0) { if (len > 0) out.write(buf, 0, len); total_read += len; sendMessage(total_read, total_size, mes); len = zip.read(buf); try { Thread.sleep(1); } catch (InterruptedException e) { } } out.flush(); out.close(); } catch (java.io.IOException e) { sendMessage(-2, 0, "Failed to write: " + e.toString()); return -1; } return 0; }
/** * Puts the uninstaller. * * @exception Exception Description of the Exception */ private void putUninstaller() throws Exception { // Me make the .uninstaller directory String dest = translatePath("$INSTALL_PATH") + File.separator + "Uninstaller"; String jar = dest + File.separator + "uninstaller.jar"; File pathMaker = new File(dest); pathMaker.mkdirs(); // We log the uninstaller deletion information UninstallData udata = UninstallData.getInstance(); udata.setUninstallerJarFilename(jar); udata.setUninstallerPath(dest); // We open our final jar file FileOutputStream out = new FileOutputStream(jar); ZipOutputStream outJar = new ZipOutputStream(out); idata.uninstallOutJar = outJar; outJar.setLevel(9); udata.addFile(jar); // We copy the uninstaller InputStream in = getClass().getResourceAsStream("/res/IzPack.uninstaller"); ZipInputStream inRes = new ZipInputStream(in); ZipEntry zentry = inRes.getNextEntry(); while (zentry != null) { // Puts a new entry outJar.putNextEntry(new ZipEntry(zentry.getName())); // Byte to byte copy int unc = inRes.read(); while (unc != -1) { outJar.write(unc); unc = inRes.read(); } // Next one please inRes.closeEntry(); outJar.closeEntry(); zentry = inRes.getNextEntry(); } inRes.close(); // We put the langpack in = getClass().getResourceAsStream("/langpacks/" + idata.localeISO3 + ".xml"); outJar.putNextEntry(new ZipEntry("langpack.xml")); int read = in.read(); while (read != -1) { outJar.write(read); read = in.read(); } outJar.closeEntry(); }
@Override /** * Examine the calendar.txt file inside the gtfsZipFile and return a list of ServiceDateRanges. */ public List<ServiceDateRange> getServiceDateRanges(InputStream gtfsZipFile) { ZipInputStream zis = null; try { zis = new ZipInputStream(gtfsZipFile); ZipEntry entry = null; String agencyId = null; String calendarFile = null; while ((entry = zis.getNextEntry()) != null) { if ("agency.txt".equals(entry.getName())) { byte[] buff = new byte[CHUNK_SIZE]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); int count = 0; while ((count = zis.read(buff, 0, CHUNK_SIZE)) != -1) { baos.write(buff, 0, count); } agencyId = parseAgencyId(baos.toString()); } if ("calendar.txt".equals(entry.getName())) { byte[] buff = new byte[CHUNK_SIZE]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); int count = 0; while ((count = zis.read(buff, 0, CHUNK_SIZE)) != -1) { baos.write(buff, 0, count); } calendarFile = baos.toString(); } } if (agencyId != null && calendarFile != null) { return convertToServiceDateRange(agencyId, calendarFile); } return null; // did not find calendar.txt } catch (IOException ioe) { throw new RuntimeException(ioe); } finally { if (zis != null) { try { zis.close(); } catch (IOException ioe) { // bury } } } }
public static Serializable unSerial(final byte[] b, final boolean zip) throws Exception { if (b == null || b.length == 0) { return null; } final ByteArrayInputStream bis = new ByteArrayInputStream(b); if (zip) { ZipInputStream zis = null; try { zis = new ZipInputStream(bis); if (zis.getNextEntry() != null) { int count; final byte data[] = new byte[2048]; final ByteArrayOutputStream bos = new ByteArrayOutputStream(); while ((count = zis.read(data, 0, 2048)) != -1) { bos.write(data, 0, count); } final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray())); return (Serializable) ois.readObject(); } return null; } finally { if (zis != null) { zis.close(); } } } final ObjectInputStream ois = new ObjectInputStream(bis); return (Serializable) ois.readObject(); }
public static boolean descomprimirEnZip(String nombreADescomprimir, String nombreDescomprimido) { try { // Abrimos el fichero ZIP String inFilename = nombreADescomprimir; ZipInputStream in = new ZipInputStream(new FileInputStream(inFilename)); // Necesario para autoasignar el unico fichero comprimido para leer ZipEntry entry = in.getNextEntry(); // Abrimos el fichero de salida String outFilename = nombreDescomprimido; OutputStream out = new FileOutputStream(outFilename); // Empezamos a transferir del fichero comprimido al descomprimido byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } // Cerramos los ficheros out.close(); in.close(); return true; } catch (IOException e) { return false; } }
private void Unzip(String outpath, int res) { final int BUFFER = 2048; InputStream xmlzip = context.getResources().openRawResource(res); ZipInputStream zis = new ZipInputStream(new BufferedInputStream(xmlzip)); BufferedOutputStream dest = null; ; ZipEntry entry = null; String finalpath = outpath; try { while ((entry = zis.getNextEntry()) != null) { if (entry.isDirectory()) { finalpath = outpath + entry.getName() + "/"; File newDir = new File(finalpath); newDir.mkdirs(); } else { int count; byte[] data = new byte[BUFFER]; FileOutputStream out = new FileOutputStream(outpath + entry.getName()); dest = new BufferedOutputStream(out, BUFFER); while ((count = zis.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** * Unzip given file into given folder. * * @param fileZip : zip file to unzip. * @param dirOut : folder where to put the unzipped files. */ public static void unzip(File fileZip, File dirOut) { try { byte[] buf = new byte[10 * 1024]; if (!fileZip.canRead()) throw new IllegalArgumentException(fileZip.getAbsolutePath()); if (!dirOut.isDirectory()) dirOut.mkdirs(); if (!dirOut.isDirectory()) throw new IllegalArgumentException(dirOut.getAbsolutePath()); FileInputStream fin = new FileInputStream(fileZip); ZipInputStream zin = new ZipInputStream(fin); ZipEntry ze = null; while ((ze = zin.getNextEntry()) != null) { File fileZe = new File(dirOut, ze.getName()); Log.i("Zip", fileZe.getAbsolutePath()); if (ze.isDirectory()) continue; assureParentExists(fileZe); BufferedOutputStream fout = new BufferedOutputStream(new FileOutputStream(fileZe)); while (true) { int read = zin.read(buf); if (-1 == read) break; // End of file. fout.write(buf, 0, read); } zin.closeEntry(); fout.close(); } zin.close(); } catch (Exception e) { Log.e("MyZip", "unzip", e); } }
public static boolean unpackFileFromZip(Path zipfile, String filename, Path destDirectory) throws IOException { boolean ret = true; byte[] bytebuffer = new byte[BUFFERSIZE]; ZipInputStream zipinputstream = new ZipInputStream(new FileInputStream(zipfile.toFile())); ZipEntry zipentry; while ((zipentry = zipinputstream.getNextEntry()) != null) { if (zipentry.getName().equals(filename)) { Path newFile = destDirectory.resolve(zipentry.getName()); FileOutputStream fileoutputstream = new FileOutputStream(newFile.toFile()); int bytes; while ((bytes = zipinputstream.read(bytebuffer)) > -1) { fileoutputstream.write(bytebuffer, 0, bytes); } fileoutputstream.close(); zipinputstream.closeEntry(); zipinputstream.close(); return ret; } zipinputstream.closeEntry(); } zipinputstream.close(); return ret; }
public void processInDirectory() { // // распакуем все файлы из каталага in // final int BUFFER_SIZE = 4096; SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); final String sessionDate = df.format(new Date()); // // ищем файлы с ответом logger.info("Обрабатываем входной каталог " + ABS_INPUT_DIR); try { File[] directoryList = (new File(ABS_INPUT_DIR)) .listFiles( pathname -> !pathname.isDirectory() && pathname.getName().endsWith(".zip")); // // распаковываем каждый zip // for (File curFile : directoryList) { logger.info("Распаковываем " + curFile.getName()); // // открываем архив // FileInputStream fis = new FileInputStream(curFile); ZipInputStream zis = new ZipInputStream(fis); ZipEntry zipEntry; while ((zipEntry = zis.getNextEntry()) != null) { // // пропускаем директории, т.к. их быть не должно // if (zipEntry.isDirectory()) continue; // // из архива извлекаем только xml !!! // if (zipEntry.getName().endsWith(".xml")) { File unzippedFile = new File(ABS_INPUT_DIR + "/" + zipEntry.getName()); logger.info("Извлекаем файл " + zipEntry.getName()); FileOutputStream fos = new FileOutputStream(unzippedFile); byte[] buffer = new byte[BUFFER_SIZE]; int count = 0; while ((count = zis.read(buffer)) > 0) { fos.write(buffer, 0, count); } fos.close(); } zis.closeEntry(); } zis.close(); fis.close(); Files.move( curFile.toPath(), Paths.get(ABS_ARCH_IN_DIR + "/" + sessionDate + "-" + curFile.getName())); } } catch (Exception e) { logger.error(e.getMessage()); e.printStackTrace(); } logger.info("Обработан входной каталог " + ABS_INPUT_DIR); }
/** * 真正的解压方法 会删除解压完的所有Zip文档 * * @param File 一个。zip的 文件 */ public static void myzijide(File file) throws IOException { ZipInputStream zip = new ZipInputStream(new FileInputStream(file)); ZipEntry en = null; BufferedOutputStream out = null; // 循环读取ZIP文件中的内容 while ((en = zip.getNextEntry()) != null) { if (en.isDirectory()) { File f = new File(file.getParent() + "\\" + en.getName()); if (!f.exists()) f.mkdirs(); continue; } // 发现好多文件夹存在 Thumbs , 定一个识别将他过滤 // 文件名中含有Thumbs 将 不 解压 if (en.getName().contains("Thumbs")) { continue; } // 实际的输出方法 out = new BufferedOutputStream(new FileOutputStream(file.getParent() + "\\" + en.getName())); int i = -1; byte[] b = new byte[1024]; while ((i = zip.read(b)) != -1) { out.write(b, 0, i); } out.close(); } zip.close(); // 删除文件 String tishi = file.delete() ? "yes" : "no"; System.out.println(file.getName() + "解压完成并删除 ?" + tishi); }
private static void unzip(File src, File dest) throws IOException { InputStream is = new FileInputStream(src); ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is)); ZipEntry ze; dest.mkdirs(); while ((ze = zis.getNextEntry()) != null) { byte[] buffer = new byte[16384]; int count; FileOutputStream fos = new FileOutputStream(new File(dest, ze.getName())); BufferedOutputStream out = new BufferedOutputStream(fos); try { while ((count = zis.read(buffer)) != -1) { out.write(buffer, 0, count); } out.flush(); } finally { fos.getFD().sync(); out.close(); } zis.closeEntry(); } zis.close(); }
public static void unZipFile(String targetPath, InputStream is) throws JDependException { try { ZipInputStream zis = new ZipInputStream(is); ZipEntry entry = null; while ((entry = zis.getNextEntry()) != null) { String zipPath = entry.getName(); if (entry.isDirectory()) { File zipFolder = new File(targetPath + File.separator + zipPath); if (!zipFolder.exists()) { zipFolder.mkdirs(); } } else { File file = new File(targetPath + File.separator + zipPath); if (!file.exists()) { File pathDir = file.getParentFile(); pathDir.mkdirs(); file.createNewFile(); // copy data FileOutputStream fos = new FileOutputStream(file); int bread; while ((bread = zis.read()) != -1) { fos.write(bread); } fos.close(); } } } zis.close(); is.close(); } catch (Exception e) { e.printStackTrace(); throw new JDependException("解压失败", e); } }
public static void unzip(InputStream is, File destDir) throws IOException { final int BUFFER = 2048; ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is)); try { ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { if (entry.isDirectory()) { File dir = new File(destDir, entry.getName()); if (!dir.mkdir()) { throw new IOException("Failed to create directory " + dir); } } else { int count; byte contents[] = new byte[BUFFER]; // write the files to the disk FileOutputStream fos = new FileOutputStream(new File(destDir, entry.getName())); try { BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER); try { while ((count = zis.read(contents, 0, BUFFER)) != -1) { dest.write(contents, 0, count); } } finally { dest.close(); } } finally { fos.close(); } } } } finally { zis.close(); } }
/** * 解压zip压缩文件到指定目录 * * @param is * @param outPath * @param zipFileName * @throws Exception */ public static boolean unZip(InputStream is, String outPath, String zipFileName) { ZipInputStream inZip = null; try { inZip = new ZipInputStream(is); ZipEntry zipEntry; String szName; while ((zipEntry = inZip.getNextEntry()) != null) { szName = zipEntry.getName(); if (zipFileName != null && szName.startsWith(zipFileName + "/")) { szName = szName.substring(zipFileName.length() + 1); } if ("".equals(szName)) { continue; } if (zipEntry.isDirectory()) { if (szName.endsWith("/")) { szName = szName.substring(0, szName.length() - 1); } File folder = new File(outPath + File.separator + szName); folder.mkdirs(); } else { File file = new File(outPath + File.separator + szName); file.createNewFile(); FileOutputStream out = null; try { out = new java.io.FileOutputStream(file); int len; byte[] buffer = new byte[1024]; while ((len = inZip.read(buffer)) != -1) { out.write(buffer, 0, len); } out.flush(); } finally { if (out != null) { try { out.close(); } catch (Exception e) { e.printStackTrace(); } } } } } } catch (Exception ex) { ex.printStackTrace(); return false; } finally { if (inZip != null) { try { inZip.close(); } catch (Exception e) { e.printStackTrace(); } } } return true; }
public static void decompressAll(File zipFile, File targetDirectory) throws IOException, ZipException { if (!targetDirectory.isDirectory()) throw new IOException("2nd Parameter targetDirectory is not a valid diectory!"); byte[] buf = new byte[4096]; ZipInputStream in = new ZipInputStream(new FileInputStream(zipFile)); while (true) { // N�chsten Eintrag lesen ZipEntry entry = in.getNextEntry(); if (entry == null) { break; } // Ausgabedatei erzeugen FileOutputStream out = new FileOutputStream( targetDirectory.getAbsolutePath() + "/" + new File(entry.getName()).getName()); // Lese-Vorgang int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } out.close(); // Eintrag schlie�en in.closeEntry(); } in.close(); }
public void verify(ZipInputStream zis, byte[] buf) throws IOException { OutputStream os = new FileOutputStream("/tmp/" + filename); int n; while ((n = zis.read(buf, 0, 1024)) > -1) { os.write(buf, 0, n); } os.flush(); os.close(); ObjectMapper om = SyncUtils.getObjectMapper( new MapConfiguration( new HashMap<String, String>() { { put(ConfigProperties.FAIL_ON_UNKNOWN_IMPORT_PROPERTIES, "false"); } })); ConsumerDto c = om.readValue(new FileInputStream("/tmp/" + filename), ConsumerDto.class); assertEquals("localhost:8443/apiurl", c.getUrlApi()); assertEquals("localhost:8443/weburl", c.getUrlWeb()); assertEquals("8auuid", c.getUuid()); assertEquals("consumer_name", c.getName()); assertEquals(new ConsumerType(ConsumerTypeEnum.CANDLEPIN), c.getType()); }
// JavaDoc inherited public int read() throws IOException { if (pos >= size) { return -1; } else { return in.read(); } }
/** * 使用Java标准Zip接口解压Zip输入流. * * @param in * @param outDir * @return */ public static final Collection<File> unZip(final ZipInputStream in, final File outDir) { final Collection<File> result = new ArrayList<File>(4); try { ZipEntry entry; BufferedOutputStream out = null; final byte data[] = new byte[10240]; // 10K while (true) { out = null; try { entry = in.getNextEntry(); if (null == entry) break; // System.out.println("extract file:" + entry.getName()); int count; // write the files to the disk final File outFile = new File(outDir, entry.getName()); outFile.getParentFile().mkdirs(); out = new BufferedOutputStream(new FileOutputStream(outFile)); while ((count = in.read(data)) != -1) out.write(data, 0, count); out.flush(); // uppack success,lot it result.add(outFile); } catch (final Exception ioex) { ioex.printStackTrace(); // for debug } finally { closeIO(out); } } } catch (final Exception e) { e.printStackTrace(); // for debug } finally { closeIO(in); } return result; }
public void addFromZip(String zipFilename) throws IOException { byte[] buf = new byte[1024]; ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFilename)); try { ZipEntry entry = zin.getNextEntry(); while (entry != null) { String name = entry.getName(); names.add(name); // Add ZIP entry to output stream. out.putNextEntry(new ZipEntry(name)); // Transfer bytes from the ZIP file to the output file int len; while ((len = zin.read(buf)) > 0) { out.write(buf, 0, len); } entry = zin.getNextEntry(); } } finally { zin.close(); } }
protected void unzip(String pathToFile, String outputFolder) { System.out.println("Start unzipping: " + pathToFile + " to " + outputFolder); String pathToUnzip; if (outputFolder.equals(pathManager.getPlatformFolderInAndroidSdk())) { pathToUnzip = outputFolder; } else { pathToUnzip = outputFolder + "/" + FileUtil.getNameWithoutExtension(new File(pathToFile)); } if (new File(pathToUnzip).listFiles() != null) { System.out.println("File was already unzipped: " + pathToFile); return; } try { byte[] buf = new byte[1024]; ZipInputStream zipinputstream = null; ZipEntry zipentry; zipinputstream = new ZipInputStream(new FileInputStream(pathToFile)); zipentry = zipinputstream.getNextEntry(); try { while (zipentry != null) { String entryName = zipentry.getName(); int n; File outputFile = new File(outputFolder + "/" + entryName); if (zipentry.isDirectory()) { outputFile.mkdirs(); zipinputstream.closeEntry(); zipentry = zipinputstream.getNextEntry(); continue; } else { File parentFile = outputFile.getParentFile(); if (parentFile != null && !parentFile.exists()) { parentFile.mkdirs(); } outputFile.createNewFile(); } FileOutputStream fileoutputstream = new FileOutputStream(outputFile); try { while ((n = zipinputstream.read(buf, 0, 1024)) > -1) { fileoutputstream.write(buf, 0, n); } } finally { fileoutputstream.close(); } zipinputstream.closeEntry(); zipentry = zipinputstream.getNextEntry(); } zipinputstream.close(); } catch (IOException e) { System.err.println("Entry name: " + zipentry.getName()); e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } System.out.println("Finish unzipping: " + pathToFile + " to " + outputFolder); }
public static void unZip(String unZipfileName, String mDestPath) { if (!mDestPath.endsWith("/")) { mDestPath = mDestPath + "/"; } FileOutputStream fileOut = null; ZipInputStream zipIn = null; ZipEntry zipEntry = null; File file = null; int readedBytes = 0; byte buf[] = new byte[4096]; try { zipIn = new ZipInputStream(new BufferedInputStream(new FileInputStream(unZipfileName))); while ((zipEntry = zipIn.getNextEntry()) != null) { file = new File(mDestPath + zipEntry.getName()); if (zipEntry.isDirectory()) { file.mkdirs(); } else { // 如果指定文件的目录不存在,则创建之. File parent = file.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } fileOut = new FileOutputStream(file); while ((readedBytes = zipIn.read(buf)) > 0) { fileOut.write(buf, 0, readedBytes); } fileOut.close(); } zipIn.closeEntry(); } } catch (IOException ioe) { ioe.printStackTrace(); } }
/** * Extracts given zip to given location * * @param zipLocation - the location of the zip to be extracted * @param outputLocation - location to extract to */ public static void extractZipTo(String zipLocation, String outputLocation) { ZipInputStream zipinputstream = null; try { byte[] buf = new byte[1024]; zipinputstream = new ZipInputStream(new FileInputStream(zipLocation)); ZipEntry zipentry = zipinputstream.getNextEntry(); while (zipentry != null) { String entryName = zipentry.getName(); int n; if (!zipentry.isDirectory() && !entryName.equalsIgnoreCase("minecraft") && !entryName.equalsIgnoreCase(".minecraft") && !entryName.equalsIgnoreCase("instMods")) { new File(outputLocation + File.separator + entryName).getParentFile().mkdirs(); FileOutputStream fileoutputstream = new FileOutputStream(outputLocation + File.separator + entryName); while ((n = zipinputstream.read(buf, 0, 1024)) > -1) { fileoutputstream.write(buf, 0, n); } fileoutputstream.close(); } zipinputstream.closeEntry(); zipentry = zipinputstream.getNextEntry(); } } catch (Exception e) { Logger.logError(e.getMessage(), e); backupExtract(zipLocation, outputLocation); } finally { try { zipinputstream.close(); } catch (IOException e) { } } }
/** * Add the entries from the supplied {@link ZipInputStream} to this archive instance. * * @param zipStream The zip stream. * @return This archive instance. * @throws IOException Error reading zip stream. */ public Archive addEntries(ZipInputStream zipStream) throws IOException { AssertArgument.isNotNull(zipStream, "zipStream"); try { ZipEntry zipEntry = zipStream.getNextEntry(); ByteArrayOutputStream outByteStream = new ByteArrayOutputStream(); byte[] byteReadBuffer = new byte[512]; int byteReadCount; while (zipEntry != null) { if (zipEntry.isDirectory()) { addEntry(zipEntry.getName(), (byte[]) null); } else { while ((byteReadCount = zipStream.read(byteReadBuffer)) != -1) { outByteStream.write(byteReadBuffer, 0, byteReadCount); } addEntry(zipEntry.getName(), outByteStream.toByteArray()); outByteStream.reset(); } zipEntry = zipStream.getNextEntry(); } } finally { try { zipStream.close(); } catch (IOException e) { logger.debug("Unexpected error closing EDI Mapping Model Zip stream.", e); } } return this; }
public static void unzip(byte[] content, final File destinationDir) throws IOException { byte[] buffer = new byte[BUFFER_SIZE]; ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(content)); ZipEntry zipEntry = zis.getNextEntry(); while (zipEntry != null) { String fileName = zipEntry.getName(); File file = new File(destinationDir + File.separator + fileName); if (zipEntry.isDirectory()) { ensureExistingDirectory(file); } else { ensureExistingDirectory(file.getParentFile()); FileOutputStream fos = new FileOutputStream(file); try { int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } } finally { closeQuietly(fos); } } zipEntry = zis.getNextEntry(); } zis.closeEntry(); zis.close(); }
/** Разархивация файла с БД */ private void dearchiveDB() { String zipFile = RES_ABS_PATH + File.separator + DB_ARCHIVE_NAME; String outputFolder = RES_ABS_PATH; try { ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry ze = zis.getNextEntry(); while (ze != null) { String fileName = ze.getName(); File newFile = new File(outputFolder + File.separator + fileName); System.out.println("File unzip : " + newFile.getAbsoluteFile()); new File(newFile.getParent()).mkdirs(); FileOutputStream fos = new FileOutputStream(newFile); int len; byte[] buffer = new byte[1024]; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); ze = zis.getNextEntry(); } zis.closeEntry(); zis.close(); System.out.println("File unziped"); } catch (IOException ex) { ex.printStackTrace(); } }
public void unzip(File from, String to) throws FITTESTException { try { FileInputStream fis = new FileInputStream(from); ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis, BUFFER)); ZipEntry entry = zis.getNextEntry(); while (entry != null) { int count; byte data[] = new byte[BUFFER]; File outFile = null; if (entry.isDirectory()) { outFile = new File(to, entry.getName()); outFile.mkdirs(); } else { outFile = new File(to, entry.getName()); FileOutputStream fos = new FileOutputStream(outFile); BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER); while ((count = zis.read(data, 0, BUFFER)) != -1) { bos.write(data, 0, count); } bos.flush(); bos.close(); } zis.closeEntry(); entry = zis.getNextEntry(); } zis.close(); } catch (Exception e) { throw new FITTESTException(e.getMessage()); } }
static boolean unpackZipTo(Path zipfile, Path destDirectory) throws IOException { boolean ret = true; byte[] bytebuffer = new byte[BUFFERSIZE]; ZipInputStream zipinputstream = new ZipInputStream(new FileInputStream(zipfile.toFile())); ZipEntry zipentry; while ((zipentry = zipinputstream.getNextEntry()) != null) { Path newFile = destDirectory.resolve(zipentry.getName()); if (!Files.exists(newFile.getParent(), LinkOption.NOFOLLOW_LINKS)) { Files.createDirectories(newFile.getParent()); } if (!Files.isDirectory(newFile, LinkOption.NOFOLLOW_LINKS)) { FileOutputStream fileoutputstream = new FileOutputStream(newFile.toFile()); int bytes; while ((bytes = zipinputstream.read(bytebuffer)) > -1) { fileoutputstream.write(bytebuffer, 0, bytes); } fileoutputstream.close(); } zipinputstream.closeEntry(); } zipinputstream.close(); return ret; }
public static void unzip(File zipFile, File targetDirectory) throws IOException { ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFile))); try { ZipEntry ze; int count; byte[] buffer = new byte[8192]; while ((ze = zis.getNextEntry()) != null) { File file = new File(targetDirectory, ze.getName()); File dir = ze.isDirectory() ? file : file.getParentFile(); if (!dir.isDirectory() && !dir.mkdirs()) throw new FileNotFoundException("Failed to ensure directory: " + dir.getAbsolutePath()); if (ze.isDirectory()) continue; FileOutputStream fout = new FileOutputStream(file); try { while ((count = zis.read(buffer)) != -1) fout.write(buffer, 0, count); } finally { fout.close(); } /* if time should be restored as well long time = ze.getTime(); if (time > 0) file.setLastModified(time); */ } } finally { zis.close(); } }
/** * Copies your database from your local assets-folder to the just created empty database in the * system folder, from where it can be accessed and handled. This is done by transfering * bytestream. */ private void copyDataBase() throws IOException { Log.d(TAG, "copyDataBase() called with: " + ""); // Open your local db as the input stream ZipInputStream zipInputStream = new ZipInputStream(context.getAssets().open("data/" + DATABASE_NAME + ".zip")); ZipEntry entry; do { entry = zipInputStream.getNextEntry(); } while (!entry.getName().equals(DATABASE_NAME)); // InputStream myInput = context.getAssets().open(DATABASE_NAME); // Path to the just created empty db String outFileName = DATABASE_PATH + DATABASE_NAME; // Open the empty db as the output stream OutputStream myOutput = new FileOutputStream(outFileName); // transfer bytes from the inputfile to the outputfile byte[] buffer = new byte[1024]; int length; while ((length = zipInputStream.read(buffer)) > 0) { myOutput.write(buffer, 0, length); } // Close the streams myOutput.flush(); myOutput.close(); zipInputStream.close(); }
/** * 获得制定zip名称的输入流 * * @param is zip的输入流 * @param reportName 要获得的zip输入流名称 * @return 流 */ @SuppressWarnings("unchecked") public static void getZipReportInputStreamMap(InputStream is, Map<Object, Object> parameters) { ZipInputStream zis = new ZipInputStream(is); BufferedOutputStream dest = null; ZipEntry entry = null; ByteArrayOutputStream fos = null; try { while ((entry = zis.getNextEntry()) != null) { int count; byte data[] = new byte[BUFFER]; // write the files to the disk fos = new ByteArrayOutputStream((int) entry.getSize()); dest = new BufferedOutputStream(fos, BUFFER); while ((count = zis.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); parameters.put(entry.getName(), new ByteArrayInputStream(fos.toByteArray())); } zis.close(); } catch (Exception e) { throw new ApplicationRuntimeException(e); } }