public static void main(String[] args) throws Exception { // create a zip file, and read it in as a byte array Path path = Files.createTempFile("bad", ".zip"); try (OutputStream os = Files.newOutputStream(path); ZipOutputStream zos = new ZipOutputStream(os)) { ZipEntry e = new ZipEntry("x"); zos.putNextEntry(e); zos.write((int) 'x'); } int len = (int) Files.size(path); byte[] data = new byte[len]; try (InputStream is = Files.newInputStream(path)) { is.read(data); } Files.delete(path); // year, month, day are zero testDate(data.clone(), 0, LocalDate.of(1979, 11, 30)); // only year is zero testDate(data.clone(), 0 << 25 | 4 << 21 | 5 << 16, LocalDate.of(1980, 4, 5)); }
/** * Compresses a collection of files to a destination zip file * @param listFiles A collection of files and directories * @param destZipFile The path of the destination zip file * @throws FileNotFoundException * @throws IOException */ public void compressFiles(List<File> listFiles, String destZipFile) throws FileNotFoundException, IOException { ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(destZipFile)); for (File file : listFiles) { if (file.isDirectory()) { addFolderToZip(file, file.getName(), zos); } else { addFileToZip(file, zos); } } zos.flush(); zos.close(); }
public static void zipFolder(String folderToZip, String destZipFile) { try { FileOutputStream fileWriter = new FileOutputStream(destZipFile); ZipOutputStream zip = new ZipOutputStream(fileWriter); addFolderToZip("", folderToZip, zip); zip.flush(); zip.close(); } catch(Exception e) { e.printStackTrace(); } }
/** 코드를 다운로드함. * @param code * @param os */ public void dowloadCode(Code code, OutputStream os){ try { ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(os),Charset.forName("8859_1")); for(SimpleCode simpleCode :code.getCodes()){ zip.putNextEntry(new ZipEntry(new String (simpleCode.getFileName().getBytes(),"8859_1") )); if(WebUtil.isCodeName(new String(simpleCode.getFileName().getBytes("8859_1"),"EUC-KR"))) zip.write(simpleCode.getContent().getBytes("EUC-KR")); else zip.write(simpleCode.getContent().getBytes("8859_1")); } code.download(); codeDao.update(code); zip.close(); } catch(Exception e) { System.err.println(e.getMessage()); } }
private static File createTestFile(int compression) throws Exception { File tempZipFile = File.createTempFile("test-data" + compression, ".zip"); tempZipFile.deleteOnExit(); try (FileOutputStream fos = new FileOutputStream(tempZipFile); ZipOutputStream zos = new ZipOutputStream(fos)) { zos.setLevel(compression); for (int i = 0; i < ZIP_ENTRY_NUM; i++) { String text = "Entry" + i; ZipEntry entry = new ZipEntry(text); zos.putNextEntry(entry); try { zos.write(data[i], 0, data[i].length); } finally { zos.closeEntry(); } } } return tempZipFile; }
private void processFiles(ZipOutputStream outputStream, Iterable<? extends File> files, byte[] buffer, HashSet<String> seenPaths, Map<String, List<String>> services, ProgressLogger progressLogger) throws Exception { PercentageProgressFormatter progressFormatter = new PercentageProgressFormatter("Generating", Iterables.size(files) + ADDITIONAL_PROGRESS_STEPS); for (File file : files) { progressLogger.progress(progressFormatter.getProgress()); if (file.getName().endsWith(".jar")) { processJarFile(outputStream, file, buffer, seenPaths, services); } else { processDirectory(outputStream, file, buffer, seenPaths, services); } progressFormatter.increment(); } writeServiceFiles(outputStream, services); progressLogger.progress(progressFormatter.incrementAndGetProgress()); writeIdentifyingMarkerFile(outputStream); progressLogger.progress(progressFormatter.incrementAndGetProgress()); }
private static void addFolderToZip(String path, String srcFolder, ZipOutputStream zip) throws Exception { File folder = new File(srcFolder); for (String fileName : folder.list()) { if (path.equals("")) { addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip); } else { addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip); } } }
@Override public void saveResultsFile(Document doc, Element root, ZipOutputStream zos) throws IOException { int algo, numRes = clusterOperation.size(); String algoName; for (int i = 0; i < numRes; i++) { algo = clusterOperation.get(i).getClusteringType(); algoName = String.valueOf(clusterOperation.get(i).getName()); algoName += "_" + i; zos.putNextEntry(new ZipEntry(algoName + JwatSession.BINext)); switch (algo) { case JWATConstants.KMEANS: saveKmeansData(zos, (KMean) clusterOperation.get(i)); break; case JWATConstants.FUZZYK: saveFuzzyData(zos, (FuzzyKMean) clusterOperation.get(i)); break; } zos.closeEntry(); } }
/** * * @param map key压缩条目路径 value重命名 * @param zipPath 压缩文件路径 * @return * @throws IOException */ public static boolean compress(Map<String, String> map, String zipPath) throws IOException { ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipPath)); for (Map.Entry<String, String> entry : map.entrySet()) { File file = new File(entry.getKey()); if (file.exists()) { InputStream inputStream = new FileInputStream(file); ZipEntry zipEntry = new ZipEntry(entry.getValue()); zipOutputStream.putNextEntry(zipEntry); int len = inputStream.read(); while (len != -1) { zipOutputStream.write(len); len = inputStream.read(); } inputStream.close(); } } zipOutputStream.close(); return true; }
/** * Compactar uma arquivo. * @param inputFile informar o arquivo a ser compactado. * @param zipFilePath informar o nome e caminho zip. * @param iZipFile se necessário, informar uma {@link IZipFile}. * @throws IOException */ public static void zipFile(File inputFile, String zipFilePath, IZipFile iZipFile) throws IOException { FileOutputStream fileOutputStream = new FileOutputStream(zipFilePath); ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream); ZipEntry zipEntry = new ZipEntry(inputFile.getName()); zipOutputStream.putNextEntry(zipEntry); FileInputStream fileInputStream = new FileInputStream(inputFile); FileChannel fileChannel = fileInputStream.getChannel(); FileLock fileLock = fileChannel.tryLock(0L, Long.MAX_VALUE, /*shared*/true); long sizeToZip = fileInputStream.available(); long sizeCompacted = 0; try { byte[] buf = new byte[1024]; int bytesRead; while ((bytesRead = fileInputStream.read(buf)) > 0) { sizeCompacted += bytesRead; zipOutputStream.write(buf, 0, bytesRead); if (iZipFile != null) iZipFile.progress(sizeToZip, sizeCompacted); } } finally { fileLock.release(); zipOutputStream.closeEntry(); zipOutputStream.close(); fileOutputStream.close(); } }
public void testGetFileForInputWithCachingArchive() throws Exception { final File wd = getWorkDir(); final File archiveFile = new File (wd, "src.zip"); final ZipOutputStream out = new ZipOutputStream(new FileOutputStream(archiveFile)); try { out.putNextEntry(new ZipEntry("org/me/resources/test.txt")); out.write("test".getBytes()); } finally { out.close(); } final URL archiveRoot = FileUtil.getArchiveRoot(Utilities.toURI(archiveFile).toURL()); final URI expectedURI = new URL (archiveRoot.toExternalForm()+"org/me/resources/test.txt").toURI(); doTestGetFileForInput(ClassPathSupport.createClassPath(archiveRoot), Arrays.asList( Pair.<Pair<String,String>,URI>of(Pair.<String,String>of("","org/me/resources/test.txt"), expectedURI), Pair.<Pair<String,String>,URI>of(Pair.<String,String>of("org.me","resources/test.txt"), expectedURI), Pair.<Pair<String,String>,URI>of(Pair.<String,String>of("org.me","resources/doesnotexist.txt"), null) )); }
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); copyToZipStream(f, anEntry, zos); } } } } }
@Test public void testLoadLoinc() throws Exception { ourLog.info("TEST = testLoadLoinc()"); ByteArrayOutputStream bos1 = new ByteArrayOutputStream(); ZipOutputStream zos1 = new ZipOutputStream(bos1); addEntry(zos1, "/loinc/", "loinc.csv"); zos1.close(); ourLog.info("ZIP file has {} bytes", bos1.toByteArray().length); ByteArrayOutputStream bos2 = new ByteArrayOutputStream(); ZipOutputStream zos2 = new ZipOutputStream(bos2); addEntry(zos2, "/loinc/", "LOINC_2.54_MULTI-AXIAL_HIERARCHY.CSV"); zos2.close(); ourLog.info("ZIP file has {} bytes", bos2.toByteArray().length); RequestDetails details = mock(RequestDetails.class); when(codeSvc.findBySystem("http://loinc.org")).thenReturn(new CodeSystemEntity()); mySvc.loadLoinc(list(bos1.toByteArray(), bos2.toByteArray()), details); verify(codeSvc).storeNewCodeSystemVersion( myCsvCaptor.capture(), any(RequestDetails.class)); CodeSystemEntity ver = myCsvCaptor.getValue(); ConceptEntity code = ver.getConcepts().iterator().next(); assertEquals("10013-1", code.getCode()); }
@Override public boolean dumpDatabase(Path path, boolean compress) { ProcessBuilder p = Exec.build(machineenv, "docker", "exec", name, "pg_dumpall", "-U", "postgres", "-c"); p.redirectOutput(Redirect.appendTo(path.toFile())); int ret = Exec.execit(p, null); if ((ret == 0) && compress) { try { ZipOutputStream out = new ZipOutputStream(new FileOutputStream(path.toFile()+".zip")); out.putNextEntry(new ZipEntry(path.getFileName().toString())); FileInputStream in = new FileInputStream(path.toFile()); IOUtils.copy(in, out); IOUtils.closeQuietly(out); IOUtils.closeQuietly(in); Files.deleteIfExists(path); } catch (Exception ioe) { log.log(Level.INFO, "Unable to compress database backup: " + ioe, ioe); } } return ret == 0; }
@Override public boolean write(OutputStream out, ProgressReporter progressReporter) throws SerializerException { if (getMode() == Mode.BODY) { try { ZipOutputStream zipOutputStream = new ZipOutputStream(out); zipOutputStream.putNextEntry(new ZipEntry("doc.kml")); writeKmlFile(zipOutputStream); zipOutputStream.closeEntry(); zipOutputStream.putNextEntry(new ZipEntry("files/collada.dae")); ifcToCollada.writeToOutputStream(zipOutputStream, progressReporter); zipOutputStream.closeEntry(); zipOutputStream.finish(); zipOutputStream.flush(); } catch (IOException e) { LOGGER.error("", e); } setMode(Mode.FINISHED); return true; } else if (getMode() == Mode.HEADER) { setMode(Mode.BODY); return true; } else if (getMode() == Mode.FINISHED) { return false; } return false; }
/** Adds build.info file with product, os, java version to zip file. */ private static void createProductInfo(ZipOutputStream out) throws IOException { String productVersion = MessageFormat.format( NbBundle.getBundle("org.netbeans.core.startup.Bundle").getString("currentVersion"), //NOI18N new Object[]{System.getProperty("netbeans.buildnumber")}); //NOI18N String os = System.getProperty("os.name", "unknown") + ", " + //NOI18N System.getProperty("os.version", "unknown") + ", " + //NOI18N System.getProperty("os.arch", "unknown"); //NOI18N String java = System.getProperty("java.version", "unknown") + ", " + //NOI18N System.getProperty("java.vm.name", "unknown") + ", " + //NOI18N System.getProperty("java.vm.version", ""); //NOI18N out.putNextEntry(new ZipEntry("build.info")); //NOI18N PrintWriter writer = new PrintWriter(out); writer.println("NetbeansBuildnumber=" + System.getProperty("netbeans.buildnumber")); //NOI18N writer.println("ProductVersion=" + productVersion); //NOI18N writer.println("OS=" + os); //NOI18N writer.println("Java=" + java); //NOI18Nv writer.println("Userdir=" + System.getProperty("netbeans.user")); //NOI18N writer.flush(); // Complete the entry out.closeEntry(); }
private ByteArrayOutputStream zipEntries(List<Pair<String, byte[]>> entryList) throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(8192); try (ZipOutputStream jar = new ZipOutputStream(buffer)) { jar.setMethod(ZipOutputStream.STORED); final CRC32 crc = new CRC32(); for (Pair<String, byte[]> entry : entryList) { byte[] bytes = entry.second; final ZipEntry newEntry = new ZipEntry(entry.first); newEntry.setMethod(ZipEntry.STORED); // chose STORED method crc.reset(); crc.update(entry.second); newEntry.setCrc(crc.getValue()); newEntry.setSize(bytes.length); writeEntryToJar(newEntry, bytes, jar); } jar.flush(); } return buffer; }
static private void addFileToZip(String path, String srcFile, ZipOutputStream zip) throws Exception { File folder = new File(srcFile); if (folder.isDirectory()) { addFolderToZip(path, srcFile, zip); } else { byte[] buf = new byte[1024]; int len; FileInputStream in = new FileInputStream(srcFile); zip.putNextEntry(new ZipEntry(path + "/" + folder.getName())); while ((len = in.read(buf)) > 0) { zip.write(buf, 0, len); } in.close(); } }
/** * Combines multiple files into a ZIP archive, then base-64 the ZIP archive. * * @param paths a list of one or more input files, that are to be compressed together * @return the compressed output, as a String */ private static String zipBase64(List<Path> paths) { if (paths.isEmpty()) { throw new IllegalArgumentException("PortfolioDataFile requires at least one file"); } try { try (ByteArrayOutputStream baos = new ByteArrayOutputStream(1024 * 8)) { try (OutputStream baseos = Base64.getEncoder().wrap(baos)) { try (ZipOutputStream zos = new ZipOutputStream(baseos)) { for (Path path : paths) { ZipEntry entry = new ZipEntry(path.getFileName().toString()); zos.putNextEntry(entry); Files.copy(path, zos); zos.closeEntry(); } } } return baos.toString("ISO-8859-1"); // base-64 bytes are ASCII, so this is optimal } } catch (IOException ex) { throw new UncheckedIOException("Failed to zip base-64 content", ex); } }
private static void copyToZipStream(File file, ZipEntry entry, ZipOutputStream zos) throws IOException { InputStream is = new FileInputStream(file); try { zos.putNextEntry(entry); byte[] arr = new byte[4096]; int read = is.read(arr); while (read > -1) { zos.write(arr, 0, read); read = is.read(arr); } } finally { try { is.close(); } finally { zos.closeEntry(); } } }
public static void createBugReport(File reportFile, Throwable exception, String userMessage, Process process, String logMessage, File[] attachments) throws IOException { ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(reportFile)); zipOut.setComment("RapidMiner bug report - generated " + new Date()); write("message.txt", "User message", userMessage, zipOut); write("_process.xml", "Process as in memory.", process.getRootOperator().getXML(false), zipOut); if (process.getProcessLocation() != null) { try { String contents = process.getProcessLocation().getRawXML(); write(process.getProcessLocation().getShortName(), "Raw process file in repository.", contents, zipOut); } catch (Throwable t) { write(process.getProcessLocation().getShortName(), "Raw process file in repository.", "could not read: " + t, zipOut); } } write("_log.txt", "Log message", logMessage, zipOut); write("_properties.txt", "System properties, information about java version and operating system", getProperties(), zipOut); write("_exception.txt", "Exception stack trace", getStackTrace(exception), zipOut); for (File attachment : attachments) { writeFile(attachment, zipOut); } zipOut.close(); }
private void addFiles(ZipOutputStream output, byte[] buf, File[] files) throws IOException { for (File file : files) { if (file.isDirectory()) { addFiles(output, buf, file.listFiles()); } else { output.putNextEntry( new ZipEntry( relativizePath( getBaseDir(mContext).getParentFile(), file))); FileInputStream input = new FileInputStream(file); try { copy(input, output, buf); } finally { input.close(); } } } }
private static void compressFile(String currentDir, ZipOutputStream zout, File[] files) throws Exception { byte[] buffer = new byte[1024]; for (File fi : files) { if (fi.isDirectory()) { compressFile(currentDir + "/" + fi.getName(), zout, fi.listFiles()); continue; } ZipEntry ze = new ZipEntry(currentDir + "/" + fi.getName()); FileInputStream fin = new FileInputStream(fi.getPath()); zout.putNextEntry(ze); int length; while ((length = fin.read(buffer)) > 0) { zout.write(buffer, 0, length); } zout.closeEntry(); fin.close(); } }
public void buildUnknownFiles(File appDir, File outFile, MetaInfo meta) throws AndrolibException { if (meta.unknownFiles != null) { LOGGER.info("Copying unknown files/dir..."); Map<String, String> files = meta.unknownFiles; File tempFile = new File(outFile.getParent(), outFile.getName() + ".apktool_temp"); boolean renamed = outFile.renameTo(tempFile); if(!renamed) { throw new AndrolibException("Unable to rename temporary file"); } try { ZipFile inputFile = new ZipFile(tempFile); ZipOutputStream actualOutput = new ZipOutputStream(new FileOutputStream(outFile)); copyExistingFiles(inputFile, actualOutput); copyUnknownFiles(appDir, actualOutput, files); actualOutput.close(); } catch (IOException ex) { throw new AndrolibException(ex); } // Remove our temporary file. tempFile.delete(); } }
/** * 压缩文件 * * @param resFile 需要压缩的文件(夹) * @param zipout 压缩的目的文件 * @param rootpath 压缩的文件路径 * @throws FileNotFoundException 找不到文件时抛出 * @throws IOException 当压缩过程出错时抛出 */ private static void zipFile(File resFile, ZipOutputStream zipout, String rootpath) throws FileNotFoundException, IOException { rootpath = rootpath + (rootpath.trim().length() == 0 ? "" : File.separator) + resFile.getName(); rootpath = new String(rootpath.getBytes("8859_1"), "GB2312"); if (resFile.isDirectory()) { File[] fileList = resFile.listFiles(); for (File file : fileList) { zipFile(file, zipout, rootpath); } } else { byte buffer[] = new byte[BUFF_SIZE]; BufferedInputStream in = new BufferedInputStream(new FileInputStream(resFile), BUFF_SIZE); zipout.putNextEntry(new ZipEntry(rootpath)); int realLength; while ((realLength = in.read(buffer)) != -1) { zipout.write(buffer, 0, realLength); } in.close(); zipout.flush(); zipout.closeEntry(); } }
@Override protected byte[] getCompressedData() throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try (ZipOutputStream os = new ZipOutputStream(bos)) { ZipEntry entry1 = new ZipEntry("data.xiidm"); byte[] data = getUncompressedData(); entry1.setSize(data.length); os.putNextEntry(entry1); os.write(data); os.closeEntry(); ZipEntry entry2 = new ZipEntry("extra_data.xiidm"); byte[] extraData = getExtraUncompressedData(); entry2.setSize(extraData.length); os.putNextEntry(entry2); os.write(extraData); os.closeEntry(); } return bos.toByteArray(); }
/** * Zip all the files in our * @param dest * @throws IOException */ private void zipfiles(File dest) throws IOException { FileOutputStream fos = new FileOutputStream(dest); ZipOutputStream zos = new ZipOutputStream(fos); for (Path p : files) { try { Path file = p.getFileName(); if (file != null) { zos.putNextEntry(new ZipEntry(file.toString())); Files.copy(p, zos); } } catch (IOException ioe) { log.warning("\bUnable to archive " + p); } zos.closeEntry(); } zos.close(); fos.close(); }
private static void zipRSScript(String outputDir, String baseFileName) { try { String outputFileName = outputDir + File.separator + baseFileName + ".zip"; String inputFileNameBitcode = outputDir + File.separator + baseFileName + ".bc"; String inputFileNameProperties = outputDir + File.separator + baseFileName + ".properties"; // Output file ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outputFileName)); addZipEntry(baseFileName + ".bc", inputFileNameBitcode, out); addZipEntry(baseFileName + ".properties", inputFileNameProperties, out); out.close(); } catch (IOException e) { e.printStackTrace(); } }
private void zip2(ZipOutputStream zos, File f, String baseDir) throws Exception { if (f.isDirectory()) { File[] fs = f.listFiles(); for (File fileSec:fs) { zip2(zos, fileSec, baseDir + f.getName() + File.separator); } } else { byte[] buf = new byte[1024]; InputStream is = new FileInputStream(f); zos.putNextEntry(new ZipEntry(baseDir + f.getName())); int len; while ((len = is.read(buf)) != -1) { zos.write(buf, 0, len); } is.close(); } }
public static void jarDir(File dir, String relativePath, ZipOutputStream zos) throws IOException { Preconditions.checkNotNull(relativePath, "relativePath"); Preconditions.checkNotNull(zos, "zos"); // by JAR spec, if there is a manifest, it must be the first entry in the // ZIP. File manifestFile = new File(dir, JarFile.MANIFEST_NAME); ZipEntry manifestEntry = new ZipEntry(JarFile.MANIFEST_NAME); if (!manifestFile.exists()) { zos.putNextEntry(manifestEntry); new Manifest().write(new BufferedOutputStream(zos)); zos.closeEntry(); } else { copyToZipStream(manifestFile, manifestEntry, zos); } zos.closeEntry(); zipDir(dir, relativePath, zos, true); zos.close(); }
/** * Compress a single file * * @param file file * @param out file stream * @param baseDir The relative address of the file */ private static void zipSingleFile(File file, ZipOutputStream out,String baseDir) { if (!file.exists()) { return; } try { int buffer = FILE_BUFFER_SIZE; BufferedInputStream bis = new BufferedInputStream( new FileInputStream(file)); ZipEntry entry = new ZipEntry(baseDir + file.getName()); out.putNextEntry(entry); int count; byte data[] = new byte[buffer]; while ((count = bis.read(data, 0, buffer)) != -1) { out.write(data, 0, count); } bis.close(); } catch (Exception e) { throw new RuntimeException(e); } }
public Packer(final File destFile, final Signer signer, final Boolean inPlace) throws FileNotFoundException { this.inPlace = inPlace; if (inPlace) { //In codesign.py this is what we use this.zipStream = new ZipOutputStream( new DataOutputStream( new ByteArrayOutputStream(128*1024*1024-1))); //Avoid java bug https://bugs.openjdk.java.net/browse/JDK-8055949 by being able to get to max buffer size of MAX_INT-16 zipStream.setLevel(Deflater.NO_COMPRESSION); } else { this.zipStream = new ZipOutputStream( new BufferedOutputStream( new FileOutputStream(destFile))); } this.signer = signer; }
private void addManifest(ByteArrayOutputStream manifest, ZipOutputStream zipout) throws IOException { if (manifest.size() > 0) { zipout.putNextEntry(new ZipEntry(MANIFEST_FILE_NAME)); byte[] manifestBytes = manifest.toByteArray(); if (images != null && images.size() > 0) { StringBuilder manifestBuilder = new StringBuilder(new String(manifestBytes, UTF8)); for (Map.Entry<String, Image> img : images.entrySet()) { int p = manifestBuilder.indexOf(MANIFEST_END_TAG); StringBuilder sb = new StringBuilder(MANIFEST_ENTRY_1); sb.append(img.getValue().getFormat().toString().toLowerCase()); sb.append(MANIFEST_ENTRY_2).append(img.getKey()).append(MANIFEST_ENTRY_3); manifestBuilder.insert(p, sb.toString()); } manifestBytes = manifestBuilder.toString().getBytes(UTF8); } zipout.write(manifestBytes); } }
public static void main(String[] args) throws Exception { URLConnection conn = B7050028.class.getResource("B7050028.class").openConnection(); int len = conn.getContentLength(); byte[] data = new byte[len]; InputStream is = conn.getInputStream(); is.read(data); is.close(); conn.setDefaultUseCaches(false); File jar = File.createTempFile("B7050028", ".jar"); jar.deleteOnExit(); OutputStream os = new FileOutputStream(jar); ZipOutputStream zos = new ZipOutputStream(os); ZipEntry ze = new ZipEntry("B7050028.class"); ze.setMethod(ZipEntry.STORED); ze.setSize(len); CRC32 crc = new CRC32(); crc.update(data); ze.setCrc(crc.getValue()); zos.putNextEntry(ze); zos.write(data, 0, len); zos.closeEntry(); zos.finish(); zos.close(); os.close(); System.out.println(new URLClassLoader(new URL[] {new URL("jar:" + jar.toURI() + "!/")}, ClassLoader.getSystemClassLoader().getParent()).loadClass(B7050028.class.getName())); }
public static void addFileToZip(String path, String srcFile, ZipOutputStream zip) throws Exception { File folder = new File(srcFile); if (folder.isDirectory()) { addFolderToZip(path, srcFile, zip); } else { byte[] buf = new byte[1024]; int len; FileInputStream in = new FileInputStream(srcFile); zip.putNextEntry(new ZipEntry(path + "/" + folder.getName())); while ((len = in.read(buf)) > 0) { zip.write(buf, 0, len); } } }
public static void ZipFiles(List<String> filepaths, String zipFileString) throws Exception { File zipFile = new File(zipFileString); if (zipFile != null && zipFile.exists()) { zipFile.delete(); } if (filepaths != null) { ZipOutputStream outZip = new ZipOutputStream(new FileOutputStream(zipFileString)); for (String filepath : filepaths) { File file = new File(filepath); if (file != null && file.exists()) { ZipEntry zipEntry = new ZipEntry(file.getName()); FileInputStream inputStream = new FileInputStream(file); outZip.putNextEntry(zipEntry); int len; byte[] buffer = new byte[4096]; while ((len = inputStream.read(buffer)) != -1) { outZip.write(buffer, 0, len); } outZip.closeEntry(); } } outZip.finish(); outZip.close(); } }
public void writeSignatureFilesToZipOutputStream(List<SignatureFile> files, OutputStream outputStream) { ZipOutputStream out = new ZipOutputStream(outputStream); files.forEach( file -> { writeZipEntry(file, out); }); try { out.close(); } catch (IOException e) { e.printStackTrace(); } }
private void getZipContent(StringBuilder sb, File f) throws IOException { try(FileOutputStream fos = new FileOutputStream(f); ZipOutputStream out = new ZipOutputStream(fos)) { this.archiveMap.entrySet().stream() .sorted(Map.Entry.<String, String>comparingByValue()) .forEachOrdered(k ->addEntryToZip(sb, out, k)); } }