@VisibleForTesting static void writeAar( Path aar, final MergedAndroidData data, Path manifest, Path rtxt, Path classes) throws IOException { try (final ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(aar.toFile()))) { ZipEntry manifestEntry = new ZipEntry("AndroidManifest.xml"); zipOut.putNextEntry(manifestEntry); zipOut.write(Files.readAllBytes(manifest)); zipOut.closeEntry(); ZipEntry classJar = new ZipEntry("classes.jar"); zipOut.putNextEntry(classJar); zipOut.write(Files.readAllBytes(classes)); zipOut.closeEntry(); Files.walkFileTree( data.getResourceDirFile().toPath(), new ZipDirectoryWriter(zipOut, data.getResourceDirFile().toPath(), "res")); ZipEntry r = new ZipEntry("R.txt"); zipOut.putNextEntry(r); zipOut.write(Files.readAllBytes(rtxt)); zipOut.closeEntry(); if (data.getAssetDirFile().exists() && data.getAssetDirFile().list().length > 0) { Files.walkFileTree( data.getAssetDirFile().toPath(), new ZipDirectoryWriter(zipOut, data.getAssetDirFile().toPath(), "assets")); } } aar.toFile().setLastModified(EPOCH); }
private byte[] createMultiLevelArchive(List<String> resources, String archivePath) throws IOException { try (ByteArrayOutputStream buffer = new ByteArrayOutputStream()) { try (ZipOutputStream out = new ZipOutputStream(buffer)) { for (String resourcePath : resources) { ZipEntry entry = new ZipEntry(resourcePath); entry.setLastModifiedTime(time); out.putNextEntry(entry); try (InputStream in = getResourceAsStream(resourcePath)) { StreamUtils.copyStream(in, out); } out.closeEntry(); } ZipEntry entry = new ZipEntry("test/"); entry.setLastModifiedTime(time); out.putNextEntry(entry); out.closeEntry(); entry = new ZipEntry(archivePath); entry.setLastModifiedTime(time); out.putNextEntry(entry); try (InputStream in = new ByteArrayInputStream(createArchive(resources))) { StreamUtils.copyStream(in, out); } out.closeEntry(); } return buffer.toByteArray(); } }
public void test_1562() throws Exception { Manifest man = new Manifest(); Attributes att = man.getMainAttributes(); att.put(Attributes.Name.MANIFEST_VERSION, "1.0"); att.put(Attributes.Name.MAIN_CLASS, "foo.bar.execjartest.Foo"); File outputZip = File.createTempFile("hyts_", ".zip"); outputZip.deleteOnExit(); ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(outputZip)); File resources = Support_Resources.createTempFolder(); for (String zipClass : new String[] {"Foo", "Bar"}) { zout.putNextEntry(new ZipEntry("foo/bar/execjartest/" + zipClass + ".class")); zout.write(getResource(resources, "hyts_" + zipClass + ".ser")); } zout.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF")); man.write(zout); zout.close(); // set up the VM parameters String[] args = new String[] {"-jar", outputZip.getAbsolutePath()}; // execute the JAR and read the result String res = Support_Exec.execJava(args, null, false); assertTrue("Error executing ZIP : result returned was incorrect.", res.startsWith("FOOBAR")); }
/** * Save factorisation machine in a compressed, human readable file. * * @param out output * @throws IOException when I/O error */ public void save(OutputStream out) throws IOException { int N = m.rows(); int K = m.columns(); try (ZipOutputStream zip = new ZipOutputStream(out)) { zip.putNextEntry(new ZipEntry("info")); PrintStream ps = new PrintStream(zip); ps.println(N); ps.println(K); ps.flush(); zip.closeEntry(); zip.putNextEntry(new ZipEntry("b")); ps = new PrintStream(zip); ps.println(b); ps.flush(); zip.closeEntry(); zip.putNextEntry(new ZipEntry("w")); saveDenseDoubleMatrix1D(zip, w); zip.closeEntry(); zip.putNextEntry(new ZipEntry("m")); saveDenseDoubleMatrix2D(zip, m); zip.closeEntry(); } }
/** Compress files and directories. */ private static void compressDirectory(String relativePath, File srcPath, ZipOutputStream zip) throws IOException { if (srcPath.isDirectory()) { zip.putNextEntry(new ZipEntry(relativePath + "/" + srcPath.getName() + "/")); zip.closeEntry(); String files[] = srcPath.list(); for (int i = 0; i < files.length; i++) { compressDirectory(relativePath + "/" + srcPath.getName(), new File(srcPath, files[i]), zip); } } else { InputStream in = new FileInputStream(srcPath); try { zip.putNextEntry(new ZipEntry(relativePath + "/" + srcPath.getName())); transfer(in, zip); zip.closeEntry(); } finally { if (in != null) { in.close(); } } } }
/** Creates a new JAR file. */ void create(OutputStream out, Manifest manifest) throws IOException { ZipOutputStream zos = new JarOutputStream(out); if (flag0) { zos.setMethod(ZipOutputStream.STORED); } if (manifest != null) { if (vflag) { output(getMsg("out.added.manifest")); } ZipEntry e = new ZipEntry(MANIFEST_DIR); e.setTime(System.currentTimeMillis()); e.setSize(0); e.setCrc(0); zos.putNextEntry(e); e = new ZipEntry(MANIFEST_NAME); e.setTime(System.currentTimeMillis()); if (flag0) { crc32Manifest(e, manifest); } zos.putNextEntry(e); manifest.write(zos); zos.closeEntry(); } for (File file : entries) { addFile(zos, file); } zos.close(); }
/** * tests case when Main-Class is not in the zip launched but in another zip referenced by * Class-Path * * @throws Exception in case of troubles */ public void test_main_class_in_another_zip() throws Exception { File fooZip = File.createTempFile("hyts_", ".zip"); File barZip = File.createTempFile("hyts_", ".zip"); fooZip.deleteOnExit(); barZip.deleteOnExit(); // create the manifest Manifest man = new Manifest(); Attributes att = man.getMainAttributes(); att.put(Attributes.Name.MANIFEST_VERSION, "1.0"); att.put(Attributes.Name.MAIN_CLASS, "foo.bar.execjartest.Foo"); att.put(Attributes.Name.CLASS_PATH, fooZip.getName()); File resources = Support_Resources.createTempFolder(); ZipOutputStream zoutFoo = new ZipOutputStream(new FileOutputStream(fooZip)); zoutFoo.putNextEntry(new ZipEntry("foo/bar/execjartest/Foo.class")); zoutFoo.write(getResource(resources, "hyts_Foo.ser")); zoutFoo.close(); ZipOutputStream zoutBar = new ZipOutputStream(new FileOutputStream(barZip)); zoutBar.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF")); man.write(zoutBar); zoutBar.putNextEntry(new ZipEntry("foo/bar/execjartest/Bar.class")); zoutBar.write(getResource(resources, "hyts_Bar.ser")); zoutBar.close(); String[] args = new String[] {"-jar", barZip.getAbsolutePath()}; // execute the JAR and read the result String res = Support_Exec.execJava(args, null, false); assertTrue("Error executing JAR : result returned was incorrect.", res.startsWith("FOOBAR")); }
private void writeMoveFileImpl(File moveFile) throws IOException { ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(moveFile))); Writer out = new OutputStreamWriter(zipOut, "UTF-8"); zipOut.putNextEntry(new ZipEntry("manifest.xml")); out.write(XML_HEADER); out.write("<archive type='dashboardDataExport'>\n"); out.write(" <exported when='@" + System.currentTimeMillis() + "' />\n"); out.write(" <file name='move.xml' type='messages' version='1' />\n"); out.write("</archive>\n"); out.flush(); zipOut.closeEntry(); zipOut.putNextEntry(new ZipEntry("move.xml")); out.write(XML_HEADER); out.write("<messages>\n"); out.write( " <message type='" + escXml(getMoveMsgType()) + "' msgId='" + escXml(getMoveMsgId()) + "'>\n"); writeMoveMsgVal(out, MoveTeamDirMessageHandler.PROJECT_ID_ATTR, projectID); writeMoveMsgVal(out, MoveTeamDirMessageHandler.DIR_ATTR, newTeamDir); writeMoveMsgVal(out, MoveTeamDirMessageHandler.DIR_UNC_ATTR, newTeamDirUNC); out.write(" </message>\n"); out.write("</messages>\n"); out.flush(); zipOut.closeEntry(); zipOut.close(); }
private static void writeScriptDocumentation( Context context, ZipOutputStream out, String path, int templateType) { String[] components = path.split("/"); String language = components[components.length - 1]; byte[] indexPage = BootstrapSiteExporter.fetchContent(context, language, null, true, templateType); try { ZipEntry entry = new ZipEntry(path + "/index.html"); out.putNextEntry(entry); out.write(indexPage); out.closeEntry(); JSONArray methods = BootstrapSiteExporter.methodsForLanguage(context, language); HashSet<String> loaded = new HashSet<>(); for (int i = 0; i < methods.length(); i++) { try { JSONObject methodDef = methods.getJSONObject(i); if (methodDef.has(BootstrapSiteExporter.METHOD_ASSET_PATH)) { String[] methodComponents = methodDef.getString(BootstrapSiteExporter.METHOD_ASSET_PATH).split("/"); String page = methodComponents[methodComponents.length - 1]; if (loaded.contains(page) == false) { String pageLanguage = language; if (page.startsWith("all_")) pageLanguage = "all"; byte[] methodContent = BootstrapSiteExporter.fetchContent( context, pageLanguage, page, true, templateType); try { ZipEntry methodEntry = new ZipEntry(path + "/" + page); out.putNextEntry(methodEntry); out.write(methodContent); out.closeEntry(); } catch (ZipException e) { e.printStackTrace(); } loaded.add(page); } } } catch (JSONException e) { e.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); } }
/** * Creates a zipped file containing the construction saved in xml and i2g format plus all external * images. Intergeo File Format (Yves Kreis) */ public void writeIntergeoFile(OutputStream os, boolean includeThumbail) throws IOException { boolean isSaving = kernel.isSaving(); kernel.setSaving(true); try { // zip stream ZipOutputStream zip = new ZipOutputStream(os); OutputStreamWriter osw = new OutputStreamWriter(zip, "UTF8"); // write I2G file for construction zip.putNextEntry(new ZipEntry(I2G_FILE)); osw.write(getFullI2G()); osw.flush(); zip.closeEntry(); // write construction thumbnails if (includeThumbail) writeThumbnail(kernel.getConstruction(), zip, I2G_FILE_THUMBNAIL); // write construction images writeConstructionImages(kernel.getConstruction(), zip, I2G_IMAGES); // save macros if (kernel.hasMacros()) { // get all registered macros from kernel ArrayList macros = kernel.getAllMacros(); // write all images used by macros writeMacroImages(macros, zip, I2G_PRIVATE_IMAGES); // write all macros to one special XML file in zip zip.putNextEntry(new ZipEntry(I2G_PRIVATE + XML_FILE_MACRO)); osw.write(getFullMacroXML(macros)); osw.flush(); zip.closeEntry(); } // write library JavaScript to one special file in zip zip.putNextEntry(new ZipEntry(I2G_PRIVATE + JAVASCRIPT_FILE)); osw.write(kernel.getLibraryJavaScript()); osw.flush(); zip.closeEntry(); // write XML file for construction zip.putNextEntry(new ZipEntry(I2G_PRIVATE + XML_FILE)); osw.write(getFullXML()); osw.flush(); zip.closeEntry(); osw.close(); zip.close(); } catch (IOException e) { throw e; } finally { kernel.setSaving(isSaving); } }
public static void main(String[] args) throws Exception { Reader trainingFile = null; // Process arguments int restArgs = commandOptions.processOptions(args); // Check arguments if (restArgs != args.length) { commandOptions.printUsage(true); throw new IllegalArgumentException("Unexpected arg " + args[restArgs]); } if (trainFileOption.value == null) { commandOptions.printUsage(true); throw new IllegalArgumentException("Expected --train-file FILE"); } if (modelFileOption.value == null) { commandOptions.printUsage(true); throw new IllegalArgumentException("Expected --model-file FILE"); } // Get the CRF structure specification. ZipFile zipFile = new ZipFile(modelFileOption.value); ZipEntry zipEntry = zipFile.getEntry("crf-info.xml"); CRFInfo crfInfo = new CRFInfo(zipFile.getInputStream(zipEntry)); StringBuffer crfInfoBuffer = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(zipFile.getInputStream(zipEntry))); String line; while ((line = reader.readLine()) != null) { crfInfoBuffer.append(line).append('\n'); } reader.close(); // Create the CRF, and train it. CRF4 crf = createCRF(trainFileOption.value, crfInfo); // Create a new zip file for our output. This will overwrite // the file we used for input. ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(modelFileOption.value)); // Copy the CRF info xml to the output zip file. zos.putNextEntry(new ZipEntry("crf-info.xml")); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(zos)); writer.write(crfInfoBuffer.toString()); writer.flush(); zos.closeEntry(); // Save the CRF classifier model to the output zip file. zos.putNextEntry(new ZipEntry("crf-model.ser")); ObjectOutputStream oos = new ObjectOutputStream(zos); oos.writeObject(crf); oos.flush(); zos.closeEntry(); zos.close(); }
/** * Loop through the ZIP file, copying its entries into a new, temporary ZIP file, skipping the * entry to be deleted. Then replace the original file with the new one. */ protected Integer deleteEntry() throws XMLDataStoreException { try { ZipInputStream inStream = this.buildZipInputStream(); File outFile = this.buildTempFile(); ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(outFile)); byte[] buffer = new byte[32768]; int inCount = 0; int outCount = 0; // copy all the entries except the one to be deleted ZipEntry entry = inStream.getNextEntry(); while (entry != null) { inCount++; if (!this.getZipEntryName().equals(entry.getName())) { outCount++; outStream.putNextEntry(entry); int byteCount; while ((byteCount = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, byteCount); } outStream.closeEntry(); } entry = inStream.getNextEntry(); } inStream.close(); if (outCount == 0) { // add a dummy record to an empty file so we can close it // this is required by ZipOutputStream outStream.putNextEntry(new ZipEntry("delete.txt")); outStream.write( "This file is a place-holder. The containing ZIP file should be deleted.".getBytes()); outStream.closeEntry(); } outStream.close(); if (outCount == inCount) { // no entries were removed - just delete the temp file outFile.delete(); } else { // at least one entry removed - delete the original file this.getFile().delete(); if (outCount == 0) { // NO entries remain - just delete the temp file too outFile.delete(); } else { // entries remain - replace original file with temp file outFile.renameTo(this.getFile()); } } return new Integer(inCount - outCount); // should be 0 or 1 } catch (IOException ex) { throw XMLDataStoreException.ioException(ex); } }
protected static void zip( final StringBuilder path, final File file, final FileFilter filter, final ZipOutputStream stream, final byte[] buffer) throws IOException { if (path == null) { throw new NullPointerException("path"); } if (file == null) { throw new NullPointerException("file"); } if (!file.exists()) { throw new IllegalArgumentException("file does not exist"); } if (filter == null) { // throw new NullPointerException("filter"); } if (stream == null) { throw new NullPointerException("stream"); } if (buffer == null) { throw new NullPointerException("buffer"); } if (buffer.length == 0) { throw new IllegalArgumentException("buffer.length(" + buffer.length + ") == 0"); } if (file.isDirectory()) { stream.putNextEntry(new ZipEntry(path + file.getName() + "/")); stream.closeEntry(); final int start = path.length(); path.append(file.getName()).append("/"); for (File child : file.listFiles()) { if (filter != null && !filter.accept(child)) { continue; } zip(path, child, filter, stream, buffer); } path.delete(start, path.length()); } else { stream.putNextEntry(new ZipEntry(path + file.getName())); ByteStreams.copy(file, stream, buffer, -1L); stream.closeEntry(); } }
/** * Rename the ZIP file to a temporary file, then copy its entries back into the original ZIP file, * leaving the stream open and returning it. */ protected Writer buildWriteStream(boolean entryShouldExist) throws XMLDataStoreException { try { File inFile = this.buildTempFile(); inFile.delete(); // the file actually gets created - delete it boolean renameSucceeded = this.getFile().renameTo(inFile); ZipInputStream inStream = this.buildZipInputStream(inFile); ZipOutputStream outStream = this.buildZipOutputStream(); boolean entryActuallyExists = false; byte[] buffer = new byte[32768]; ZipEntry entry = inStream.getNextEntry(); while (entry != null) { boolean weWantToWriteTheEntry = true; if (this.getZipEntryName().equals(entry.getName())) { entryActuallyExists = true; // if we were expecting the entry, skip it; // if we were NOT expecting the entry, allow it to be rewritten // so the file is restored to its original condition if (entryShouldExist) { weWantToWriteTheEntry = false; } } if (weWantToWriteTheEntry) { outStream.putNextEntry(entry); int byteCount; while ((byteCount = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, byteCount); } outStream.closeEntry(); } entry = inStream.getNextEntry(); } // close and delete the temporary file inStream.close(); inFile.delete(); // check for invalid state if (entryShouldExist != entryActuallyExists) { outStream.close(); // close it since we will not be returning it // need more helpful exceptions here if (entryActuallyExists) { throw XMLDataStoreException.fileAlreadyExists(new File(this.getZipEntryName())); } else { throw XMLDataStoreException.fileNotFound(new File(this.getZipEntryName()), null); } } outStream.putNextEntry(new ZipEntry(this.getZipEntryName())); return new OutputStreamWriter(outStream); } catch (IOException ex) { throw XMLDataStoreException.ioException(ex); } }
public void testStream() throws Exception { // fill up a stringbuffer with some test data StringBuffer sb = new StringBuffer(); for (int i = 0; i < 1000; i++) { sb.append("DATAdataDATAdata"); } String data = sb.toString(); // create a temporary folder File tempDir = File.createTempFile("temp", "dir"); tempDir.delete(); tempDir.mkdirs(); System.out.println("Dir: " + tempDir); // create a zip file with two entries in it File zipfile = new File(tempDir, "zipfile"); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipfile)); String dummy1 = "dummy"; zos.putNextEntry(new ZipEntry(dummy1)); zos.write(data.getBytes()); zos.closeEntry(); String dummy2 = "dummy2"; zos.putNextEntry(new ZipEntry(dummy2)); zos.write(data.getBytes()); zos.closeEntry(); zos.close(); // create another temporary folder File dir = new File(tempDir, "dir"); dir.mkdirs(); File index = new File(tempDir, "list"); ExplodingOutputtingInputStream stream = new ExplodingOutputtingInputStream(new FileInputStream(zipfile), index, dir); byte[] buffer = new byte[2]; int read = stream.read(buffer); while (read != -1) { read = stream.read(buffer); } stream.close(); // create references to the unpacked dummy files File d1 = new File(dir, dummy1); File d2 = new File(dir, dummy2); // cleanup zipfile.delete(); index.delete(); d1.delete(); d2.delete(); dir.delete(); tempDir.delete(); }
/** * 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(); }
public static void main(String[] args) throws IOException { boolean exist = false; String fileName = args[0]; String zipName = args[1]; Map<ZipEntry, byte[]> map = new HashMap<>(); String fileWithoutPathName = new File(fileName).getName(); FileInputStream fis = new FileInputStream(zipName); ZipInputStream 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); } map.put(ze, baos.toByteArray()); } zis.close(); FileOutputStream fos = new FileOutputStream(zipName); ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos)); for (Map.Entry<ZipEntry, byte[]> pair : map.entrySet()) { if (fileWithoutPathName.equals(pair.getKey().getName())) { exist = true; continue; } zos.putNextEntry(pair.getKey()); zos.write(pair.getValue()); zos.closeEntry(); } if (exist) { FileInputStream fis2 = new FileInputStream(fileName); byte[] fileBytes = new byte[fis2.available()]; fis2.read(fileBytes); fis2.close(); ZipEntry zipEntry = new ZipEntry("new/" + fileWithoutPathName); zos.putNextEntry(zipEntry); zos.write(fileBytes); zos.closeEntry(); zos.close(); } else { zos.closeEntry(); zos.close(); } }
private HashCode writeSimpleJarAndGetHash() throws Exception { try (FileOutputStream fileOutputStream = new FileOutputStream(output.toFile()); ZipOutputStream out = new JarOutputStream(fileOutputStream)) { ZipEntry entry = new CustomZipEntry("test"); out.putNextEntry(entry); out.write(new byte[0]); entry = new ZipEntry("test1"); entry.setTime(ZipConstants.getFakeTime()); out.putNextEntry(entry); out.write(new byte[0]); } return Hashing.sha1().hashBytes(Files.readAllBytes(output)); }
protected void writeDocument(String path, ExportedDocument doc) throws IOException { if (path.equals("/") || path.length() == 0) { path = ""; } else { // avoid adding a root entry path += '/'; ZipEntry entry = new ZipEntry(path); // store the number of child as an extra info on the entry entry.setExtra(new DWord(doc.getFilesCount()).getBytes()); out.putNextEntry(entry); out.closeEntry(); // System.out.println(">> add entry: "+entry.getName()); } // write metadata ZipEntry entry = new ZipEntry(path + ExportConstants.DOCUMENT_FILE); out.putNextEntry(entry); try { writeXML(doc.getDocument(), out); } finally { out.closeEntry(); // System.out.println(">> add entry: "+entry.getName()); } // write external documents for (Map.Entry<String, Document> ext : doc.getDocuments().entrySet()) { String fileName = ext.getKey() + ".xml"; entry = new ZipEntry(path + fileName); out.putNextEntry(entry); try { writeXML(ext.getValue(), out); } finally { out.closeEntry(); } } // write blobs Map<String, Blob> blobs = doc.getBlobs(); for (Map.Entry<String, Blob> blobEntry : blobs.entrySet()) { String fileName = blobEntry.getKey(); entry = new ZipEntry(path + fileName); out.putNextEntry(entry); try (InputStream in = blobEntry.getValue().getStream()) { IOUtils.copy(in, out); } // DO NOT CALL out.close(), we want to keep writing to it out.closeEntry(); } }
private void addDirectory(ZipOutputStream out, File source, String directory) { // get directory contents File[] files = source.listFiles(); log.debug("Add directory: {}", directory); for (File file : files) { // if current file is a directory, call recursively if (file.isDirectory()) { // Only include certain sub-directories if (!directory.equals("") || Arrays.asList(profDirs).contains(file.getName().toLowerCase())) { try { out.putNextEntry(new ZipEntry(directory + file.getName() + "/")); } catch (IOException ex) { log.error("Exception when adding directory: " + ex); } addDirectory(out, file, directory + file.getName() + "/"); } else { log.debug("Skipping: {}{}", directory, file.getName()); } continue; } // Got here - add file try { // Only include certain files if (!directory.equals("") || file.getName().toLowerCase().matches(".*(config\\.xml|\\.properties)")) { log.debug("Add file: {}{}", directory, file.getName()); byte[] buffer = new byte[1024]; FileInputStream in = new FileInputStream(file); out.putNextEntry(new ZipEntry(directory + file.getName())); int length; while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); } out.closeEntry(); in.close(); } else { log.debug("Skip file: {}{}", directory, file.getName()); } } catch (FileNotFoundException ex) { log.error("Exception when adding file: " + ex); } catch (IOException ex) { log.error("Exception when adding file: " + ex); } } }
static void optimize(final File f) throws IOException { if (nodebug && f.getName().contains("debug")) { return; } if (f.isDirectory()) { File[] files = f.listFiles(); for (int i = 0; i < files.length; ++i) { optimize(files[i]); } } else if (f.getName().endsWith(".jar")) { File g = new File(f.getParentFile(), f.getName() + ".new"); ZipFile zf = new ZipFile(f); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(g)); Enumeration<? extends ZipEntry> e = zf.entries(); byte[] buf = new byte[10000]; while (e.hasMoreElements()) { ZipEntry ze = e.nextElement(); if (ze.isDirectory()) { out.putNextEntry(ze); continue; } out.putNextEntry(ze); if (ze.getName().endsWith(".class")) { ClassReader cr = new ClassReader(zf.getInputStream(ze)); // cr.accept(new ClassDump(), 0); cr.accept(new ClassVerifier(), 0); } InputStream is = zf.getInputStream(ze); int n; do { n = is.read(buf, 0, buf.length); if (n != -1) { out.write(buf, 0, n); } } while (n != -1); out.closeEntry(); } out.close(); zf.close(); if (!f.delete()) { throw new IOException("Cannot delete file " + f); } if (!g.renameTo(f)) { throw new IOException("Cannot rename file " + g); } } }
private static void zipDir(File dir, String relativePath, ZipOutputStream zos, boolean start) throws IOException { String[] dirList = dir.list(); for (String aDirList : dirList) { File f = new File(dir, aDirList); if (!f.isHidden()) { if (f.isDirectory()) { if (!start) { ZipEntry dirEntry = new ZipEntry(relativePath + f.getName() + "/"); zos.putNextEntry(dirEntry); zos.closeEntry(); } String filePath = f.getPath(); File file = new File(filePath); zipDir(file, relativePath + f.getName() + "/", zos, false); } else { String path = relativePath + f.getName(); if (!path.equals(JarFile.MANIFEST_NAME)) { ZipEntry anEntry = new ZipEntry(path); InputStream is = new FileInputStream(f); copyToZipStream(is, anEntry, zos); } } } } }
private static void writeStaticAssets(AssetManager assets, ZipOutputStream out, String path) { try { for (String item : assets.list(path)) { try { InputStream fileIn = assets.open(path + "/" + item); ByteArrayOutputStream baos = new ByteArrayOutputStream(); BufferedInputStream bin = new BufferedInputStream(fileIn); byte[] buffer = new byte[8192]; int read = 0; while ((read = bin.read(buffer, 0, buffer.length)) != -1) { baos.write(buffer, 0, read); } bin.close(); baos.close(); ZipEntry entry = new ZipEntry(path + "/" + item); out.putNextEntry(entry); out.write(baos.toByteArray()); out.closeEntry(); } catch (IOException e) { BootstrapSiteExporter.writeStaticAssets(assets, out, path + "/" + item); } } } catch (IOException e) { e.printStackTrace(); } }
public static String CreateZip(String[] filesToZip, String zipFileName) { byte[] buffer = new byte[18024]; try { ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); out.setLevel(Deflater.BEST_COMPRESSION); for (int i = 0; i < filesToZip.length; i++) { FileInputStream in = new FileInputStream(filesToZip[i]); String fileName = null; for (int X = filesToZip[i].length() - 1; X >= 0; X--) { if (filesToZip[i].charAt(X) == '\\' || filesToZip[i].charAt(X) == '/') { fileName = filesToZip[i].substring(X + 1); break; } else if (X == 0) fileName = filesToZip[i]; } out.putNextEntry(new ZipEntry(fileName)); int len; while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len); out.closeEntry(); in.close(); } out.close(); } catch (IllegalArgumentException e) { return "Failed to create zip: " + e.toString(); } catch (FileNotFoundException e) { return "Failed to create zip: " + e.toString(); } catch (IOException e) { return "Failed to create zip: " + e.toString(); } return "Success"; }
/** create zip file of ssh keys */ public void createZip(String publicKey, String privateKey) { // These are the files to include in the ZIP file String[] source = new String[] {publicKey, privateKey}; // Create a buffer for reading the files byte[] buf = new byte[1024]; try { // Create the ZIP file String target = privateKey + ".zip"; ZipOutputStream out = new ZipOutputStream(new FileOutputStream(target)); // Compress the files for (int i = 0; i < source.length; i++) { FileInputStream in = new FileInputStream(source[i]); // Add ZIP entry to output stream. out.putNextEntry(new ZipEntry(source[i])); // Transfer bytes from the file to the ZIP file int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } // Complete the entry out.closeEntry(); in.close(); } // Complete the ZIP file out.close(); } catch (IOException e) { } }
public void putNextEntry(String path, String content) throws IOException { ZipEntry entry = new ZipEntry(path); zipOutputStream.putNextEntry(entry); zipOutputStream.write(content.getBytes(encoding)); zipOutputStream.closeEntry(); checkSize(entry); }
@Override public void putEntry(FileLike fileLike) throws IOException { String name = fileLike.getRelativePath(); // Tracks unique entry names and avoids duplicates. This is, believe it or not, how // proguard seems to handle merging multiple -injars into a single -outjar. if (!containsEntry(fileLike)) { entryNames.add(name); outStream.putNextEntry(new ZipEntry(name)); try (InputStream in = fileLike.getInput()) { ByteStreams.copy(in, outStream); } // Make sure FileLike#getSize didn't lie (or we forgot to call canPutEntry). DalvikStatsTool.Stats stats = dalvikStatsCache.getStats(fileLike); Preconditions.checkState( !isEntryTooBig(fileLike), "Putting entry %s (%s) exceeded maximum size of %s", name, stats.estimatedLinearAllocSize, linearAllocLimit); currentLinearAllocSize += stats.estimatedLinearAllocSize; currentMethodReferences.addAll(stats.methodReferences); String report = String.format( "%d %d %s\n", stats.estimatedLinearAllocSize, stats.methodReferences.size(), name); Files.append(report, reportFile, Charsets.UTF_8); } }
/** * Write the ZIP entry to the given Zip output stream. * * @param pOutput the stream where to write the entry data. */ public void writeContentToZip(ZipOutputStream pOutput) { BufferedInputStream origin = null; try { FileInputStream fi = new FileInputStream(mResource); origin = new BufferedInputStream(fi, BUFFER_SIZE); ZipEntry entry = new ZipEntry(mEntryName); pOutput.putNextEntry(entry); int count; byte data[] = new byte[BUFFER_SIZE]; while ((count = origin.read(data, 0, BUFFER_SIZE)) != -1) { pOutput.write(data, 0, count); } pOutput.closeEntry(); } catch (IOException e) { System.err.println( "Problem when writing file to zip: " + mEntryName + " (" + e.getLocalizedMessage() + ")"); } finally { // Close the file entry stream try { if (origin != null) { origin.close(); } } catch (IOException e) { } } }
/** * Zip up a directory path * * @param directory * @param zos * @param path * @throws IOException */ private static void zipDir(String directory, ZipOutputStream zos, String path) throws IOException { File zipDir = new File(directory); // get a listing of the directory content String[] dirList = zipDir.list(); byte[] readBuffer = new byte[2156]; int bytesIn = 0; // loop through dirList, and zip the files for (int i = 0; i < dirList.length; ++i) { File f = new File(zipDir, dirList[i]); if (f.isDirectory()) { zipDir(f.getPath(), zos, path.concat(f.getName()).concat(FILE_SEPARATOR)); continue; } FileInputStream fis = new FileInputStream(f); try { zos.putNextEntry(new ZipEntry(path.concat(f.getName()))); bytesIn = fis.read(readBuffer); while (bytesIn != -1) { zos.write(readBuffer, 0, bytesIn); bytesIn = fis.read(readBuffer); } } finally { closeQuietly(fis); } } }
public static void main(String argv[]) { try { BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream("c:\\zip\\myfigs.zip"); CheckedOutputStream checksum = new CheckedOutputStream(dest, new Adler32()); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(checksum)); // out.setMethod(ZipOutputStream.DEFLATED); byte data[] = new byte[BUFFER]; // get a list of files from current directory File f = new File("."); String files[] = f.list(); for (int i = 0; i < files.length; i++) { try { System.out.println("Adding: " + files[i]); FileInputStream fi = new FileInputStream(files[i]); origin = new BufferedInputStream(fi, BUFFER); ZipEntry entry = new ZipEntry(files[i]); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) { out.write(data, 0, count); } origin.close(); } catch (Exception e) { // Ignore } } out.close(); System.out.println("checksum: " + checksum.getChecksum().getValue()); } catch (Exception e) { e.printStackTrace(); } }