Java Code Examples for java.util.zip.ZipOutputStream#putNextEntry()

The following examples show how to use java.util.zip.ZipOutputStream#putNextEntry() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ZIPUtils.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
private static void addFileToZip(String path, String srcFile, ZipOutputStream zip, boolean flag) throws IOException {
    File folder = new File(srcFile);
    if (flag) {
        zip.putNextEntry(new ZipEntry(path + "/" + folder.getName() + "/"));
    } else {
        if (folder.isDirectory()) {
            addFolderToZip(path, srcFile, zip);
        } else {
            byte[] buf = new byte[1024];
            int len;
            try (FileInputStream in = new FileInputStream(srcFile)) {
                zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
                while ((len = in.read(buf)) > 0) {
                    zip.write(buf, 0, len);
                }
            }
        }
    }
}
 
Example 2
Source File: MyZip.java    From Compressor with GNU General Public License v2.0 6 votes vote down vote up
private void dfs(File[] files, ZipOutputStream zos, String fpath)
		throws IOException {
	byte[] buf = new byte[1024];
	for (File child : files) {
		if (child.isFile()) { // 文件
			FileInputStream fis = new FileInputStream(child);
			BufferedInputStream bis = new BufferedInputStream(fis);
			zos.putNextEntry(new ZipEntry(fpath + child.getName()));
			int len;
			while((len = bis.read(buf)) > 0) {
				zos.write(buf, 0, len);
			}
			bis.close();
			zos.closeEntry();
			continue;
		}
		File[] fs = child.listFiles();
		String nfpath = fpath + child.getName() + "/";
		if (fs.length <= 0) { // 空目录
			zos.putNextEntry(new ZipEntry(nfpath));
			zos.closeEntry();
		} else { // 目录非空,递归处理
			dfs(fs, zos, nfpath);
		}
	}
}
 
Example 3
Source File: ServiceClasspathTest.java    From tomee with Apache License 2.0 6 votes vote down vote up
public File toJar() throws IOException {
    final File file = File.createTempFile("archive-", ".jar");
    file.deleteOnExit();

    // Create the ZIP file
    final ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(file)));

    for (final Map.Entry<String, byte[]> entry : entries().entrySet()) {
        out.putNextEntry(new ZipEntry(entry.getKey()));
        out.write(entry.getValue());
    }

    // Complete the ZIP file
    out.close();
    return file;
}
 
Example 4
Source File: BaseFilterTest.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
/**
 * Adds a file to a ZIP output stream.
 *
 * @param srcFile  File to add - Cannot be {@code null}.
 * @param destPath Path to use for the file - May be {@code null} or empty.
 * @param out      Destination stream - Cannot be {@code null}.
 *
 * @throws IOException Error writing to the output stream.
 */
private static void zipFile(final File srcFile, final String destPath, final ZipOutputStream out)
        throws IOException {

    final byte[] buf = new byte[1024];
    try (final InputStream in = new BufferedInputStream(new FileInputStream(srcFile))) {
        final ZipEntry zipEntry = new ZipEntry(concatPathAndFilename(destPath, srcFile.getName(), File.separator));
        zipEntry.setTime(srcFile.lastModified());
        out.putNextEntry(zipEntry);
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        out.closeEntry();
    }
}
 
Example 5
Source File: ArchiveBleach.java    From DocBleach with MIT License 6 votes vote down vote up
@Override
public void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session)
    throws BleachException {
  ZipInputStream zipIn = new ZipInputStream(inputStream);
  ZipOutputStream zipOut = new ZipOutputStream(outputStream);

  try {
    ZipEntry entry;
    while ((entry = zipIn.getNextEntry()) != null) {
      if (entry.isDirectory()) {
        LOGGER.trace("Directory: {}", entry.getName());
        ZipEntry newEntry = new ZipEntry(entry);
        zipOut.putNextEntry(newEntry);
      } else {
        LOGGER.trace("Entry: {}", entry.getName());
        sanitizeFile(session, zipIn, zipOut, entry);
      }

      zipOut.closeEntry();
    }

    zipOut.finish();
  } catch (IOException e) {
    LOGGER.error("Error in ArchiveBleach", e);
  }
}
 
Example 6
Source File: ZipEntryTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void testMaxLengthExtra() throws Exception {
  byte[] maxLengthExtra = new byte[65535];

  File f = createTemporaryZipFile();
  ZipOutputStream out = createZipOutputStream(f);
  ZipEntry ze = new ZipEntry("x");
  ze.setSize(0);
  ze.setTime(ENTRY_TIME);
  ze.setExtra(maxLengthExtra);
  out.putNextEntry(ze);
  out.closeEntry();
  out.close();

  // Read it back, and check that we see the entry.
  ZipFile zipFile = new ZipFile(f);
  assertEquals(maxLengthExtra.length, zipFile.getEntry("x").getExtra().length);
  zipFile.close();
}
 
Example 7
Source File: CompressBitmap.java    From mars-sim with GNU General Public License v3.0 6 votes vote down vote up
public static void zipStats(String filename) throws IOException {
    Path path = Paths.get(filename);
    byte[] input = Files.readAllBytes(path);
    
    System.out.println("I will try to compress the original bitmap using zip.");

    long bef = System.nanoTime();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    zos.setLevel(9);
    ZipEntry entry = new ZipEntry(filename);
    entry.setSize(input.length);
    zos.putNextEntry(entry);
    zos.write(input);
    zos.closeEntry();
    zos.close();
    
    byte[] result = baos.toByteArray();
    long aft = System.nanoTime();
    
    System.out.println("zip encoding speed:"+input.length*1000.0/(aft-bef)+" million of bytes per second");
    System.out.println("zip compression ratio at best level : "+input.length * 1.0 / result.length);
}
 
Example 8
Source File: AlbumImpl.java    From screenshot-tests-for-android with Apache License 2.0 5 votes vote down vote up
@Override
public String writeBitmap(String name, int tilei, int tilej, Bitmap bitmap) throws IOException {
  String tileName = generateTileName(name, tilei, tilej);
  String filename = getScreenshotFilenameInternal(tileName);
  ZipOutputStream zipOutputStream = getOrCreateZipOutputStream();
  ZipEntry entry = new ZipEntry(filename);
  zipOutputStream.putNextEntry(entry);
  bitmap.compress(Bitmap.CompressFormat.PNG, COMPRESSION_QUALITY, zipOutputStream);
  return tileName;
}
 
Example 9
Source File: Instrumenter.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * <p>
 * This method instruments each class file in a given jar and write the
 * instrumented one to the destination jar file
 * </p>
 * 
 * @param zis
 *            Stream for input jar
 * @param zos
 *            Stream for output jar
 
 *             If any error occurred
 */
public void instrumentJar(ZipInputStream zis, ZipOutputStream zos)
		throws IOException {
	ZipEntry entry;
	byte[] outputBytes = null;

	// execute for each entry in the jar
	while ((entry = zis.getNextEntry()) != null) {
		outputBytes = InstrumentUtil.getEntryBytesFromZip(zis);

		
		// instrument if and only if it is a class file
		if (entry.getName().endsWith(
				InstrumentConstants.CLASS_FILE_EXTENSION)) {				
			currentlyInstrumentingClass=entry.getName().replace('/', '.');
			currentlyInstrumentingClass=currentlyInstrumentingClass.substring(0,currentlyInstrumentingClass.indexOf(".class"));				

			outputBytes = instrumentEntry(outputBytes);
						}

		// create a new entry and write the bytes obtained above
		ZipEntry outputEntry = new ZipEntry(entry.getName());
		outputEntry.setComment(entry.getComment());
		outputEntry.setExtra(entry.getExtra());
		outputEntry.setTime(entry.getTime());
		zos.putNextEntry(outputEntry);
		zos.write(outputBytes);
		zos.closeEntry();
		zis.closeEntry();
	}

	// adding other files if required
	addAdditionalFiles(zos);
}
 
Example 10
Source File: LongBitSet.java    From metanome-algorithms with Apache License 2.0 5 votes vote down vote up
public void compress(OutputStream out) throws IOException {
	ZipOutputStream zOut = new ZipOutputStream(out);
	// zOut.setLevel(Deflater.BEST_SPEED);
	zOut.putNextEntry(new ZipEntry("A"));
	DataOutputStream dOut = new DataOutputStream(zOut);
	dOut.writeInt(mUnits.length);
	for (int ii = 0; ii < mUnits.length; ii++) {
		dOut.writeLong(mUnits[ii]);
	}
	dOut.flush();
	zOut.closeEntry();
	zOut.flush();
}
 
Example 11
Source File: Tools.java    From ApiManager with GNU Affero General Public License v3.0 5 votes vote down vote up
private static void writeZip(File file, String parentPath, ZipOutputStream zos) throws Exception {
    if (file.exists()) {
        if (file.isDirectory()) {// 处理文件夹
            parentPath += file.getName() + File.separator;
            File[] files = file.listFiles();
            if (files.length != 0) {
                for (File f : files) {
                    writeZip(f, parentPath, zos);
                }
            } else {
                zos.putNextEntry(new ZipEntry(parentPath));
            }
        } else {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(file);
                ZipEntry ze = new ZipEntry(parentPath + file.getName());
                zos.putNextEntry(ze);
                byte[] content = new byte[1024];
                int len;
                while ((len = fis.read(content)) != -1) {
                    zos.write(content, 0, len);
                    zos.flush();
                }
            } catch (Exception e) {
                throw e;
            } finally {
                if (fis != null) {
                    fis.close();
                }
            }
        }
    }
}
 
Example 12
Source File: DexPrinter.java    From JAADAS with GNU General Public License v3.0 5 votes vote down vote up
private void copyAllButClassesDexAndSigFiles(ZipFile source, ZipOutputStream destination) throws IOException {
	Enumeration<? extends ZipEntry> sourceEntries = source.entries();
	while (sourceEntries.hasMoreElements()) {
		ZipEntry sourceEntry = sourceEntries.nextElement();
		String sourceEntryName = sourceEntry.getName();
		if (sourceEntryName.equals(CLASSES_DEX) || isSignatureFile(sourceEntryName)) {
			continue;
		}
		// separate ZipEntry avoids compression problems due to encodings
		ZipEntry destinationEntry = new ZipEntry(sourceEntryName);
		// use the same compression method as the original (certain files are stored, not compressed)
		destinationEntry.setMethod(sourceEntry.getMethod());
		// copy other necessary fields for STORE method
		destinationEntry.setSize(sourceEntry.getSize());
		destinationEntry.setCrc(sourceEntry.getCrc());
		// finally craft new entry
		destination.putNextEntry(destinationEntry);
		InputStream zipEntryInput = source.getInputStream(sourceEntry);
		byte[] buffer = new byte[2048];
		int bytesRead = zipEntryInput.read(buffer);
		while (bytesRead > 0) {
			destination.write(buffer, 0, bytesRead);
			bytesRead = zipEntryInput.read(buffer);
		}
		zipEntryInput.close();
	}
}
 
Example 13
Source File: ZipUtils.java    From fc-java-sdk with MIT License 5 votes vote down vote up
public static void zipDir(File dir, String zipName) throws IOException {
    Preconditions.checkArgument(dir != null, "dir `"+ dir + "` cannot be null");
    Preconditions.checkArgument(dir.isDirectory(), "dir `"+ dir + "` must be a directory");
    Preconditions.checkArgument(!Strings.isNullOrEmpty(zipName), "zipName cannot be blank");
    List<String> fileNames = new ArrayList<String>();
    getFileNames(dir, fileNames);
    // zip files one by one
    // create ZipOutputStream to write to the zip file
    FileOutputStream fos = new FileOutputStream(zipName);
    ZipOutputStream zos = new ZipOutputStream(fos);
    for (String filePath : fileNames) {
        // for ZipEntry we need to keep only relative file path, so we used substring on absolute path
        ZipEntry ze = new ZipEntry(
            filePath.substring(dir.getAbsolutePath().length() + 1, filePath.length()));
        zos.putNextEntry(ze);
        // read the file and write to ZipOutputStream
        FileInputStream fis = new FileInputStream(filePath);
        byte[] buffer = new byte[1024];
        int len;
        while ((len = fis.read(buffer)) > 0) {
            zos.write(buffer, 0, len);
        }
        zos.closeEntry();
        fis.close();
    }
    zos.close();
    fos.close();
}
 
Example 14
Source File: OcspCertstoreDbExporter.java    From xipki with Apache License 2.0 5 votes vote down vote up
private void finalizeZip(ZipOutputStream zipOutStream, OcspCertstore.Certs certs)
    throws IOException {
  ZipEntry certZipEntry = new ZipEntry("certs.json");
  zipOutStream.putNextEntry(certZipEntry);
  try {
    JSON.writeJSONString(zipOutStream, Charset.forName("UTF-8"), certs);
  } finally {
    zipOutStream.closeEntry();
  }

  zipOutStream.close();
}
 
Example 15
Source File: RecursiveZipper.java    From tmc-intellij with MIT License 5 votes vote down vote up
private void writeEntry(File file, ZipOutputStream zos, String zipPath) throws IOException {
    zos.putNextEntry(new ZipEntry(zipPath + "/" + file.getName()));

    FileInputStream in = new FileInputStream(file);
    IOUtils.copy(in, zos);
    in.close();
    zos.closeEntry();
}
 
Example 16
Source File: ATSImportTool.java    From tez with Apache License 2.0 4 votes vote down vote up
/**
 * Download DAG data (DAG, Vertex, Task, TaskAttempts) from ATS and write to zip file
 *
 * @param zos
 * @throws TezException
 * @throws JSONException
 * @throws IOException
 */
private void downloadData(ZipOutputStream zos) throws TezException, JSONException, IOException {
  JSONObject finalJson = new JSONObject();

  //Download application details (TEZ_VERSION etc)
  String tezAppId = "tez_" + tezDAGID.getApplicationId().toString();
  String tezAppUrl = String.format("%s/%s/%s", baseUri, Constants.TEZ_APPLICATION, tezAppId);
  JSONObject tezAppJson = getJsonRootEntity(tezAppUrl);
  finalJson.put(Constants.APPLICATION, tezAppJson);

  //Download dag
  String dagUrl = String.format("%s/%s/%s", baseUri, Constants.TEZ_DAG_ID, dagId);
  JSONObject dagRoot = getJsonRootEntity(dagUrl);

  // We have added dag extra info, if we find any from ATS we copy the info into dag object
  // extra info.
  String dagExtraInfoUrl = String.format("%s/%s/%s", baseUri, EntityTypes.TEZ_DAG_EXTRA_INFO,
      dagId);
  JSONObject dagExtraInfo = getJsonRootEntity(dagExtraInfoUrl);
  if (dagExtraInfo.has(Constants.OTHER_INFO)) {
    JSONObject dagOtherInfo = dagRoot.getJSONObject(Constants.OTHER_INFO);
    JSONObject extraOtherInfo = dagExtraInfo.getJSONObject(Constants.OTHER_INFO);
    @SuppressWarnings("unchecked")
    Iterator<String> iter = extraOtherInfo.keys();
    while (iter.hasNext()) {
      String key = iter.next();
      dagOtherInfo.put(key, extraOtherInfo.get(key));
    }
  }
  finalJson.put(Constants.DAG, dagRoot);

  //Create a zip entry with dagId as its name.
  ZipEntry zipEntry = new ZipEntry(dagId);
  zos.putNextEntry(zipEntry);
  //Write in formatted way
  IOUtils.write(finalJson.toString(4), zos, UTF8);

  //Download vertex
  String vertexURL =
      String.format(VERTEX_QUERY_STRING, baseUri,
          Constants.TEZ_VERTEX_ID, batchSize, Constants.TEZ_DAG_ID, dagId);
  downloadJSONArrayFromATS(vertexURL, zos, Constants.VERTICES);

  //Download task
  String taskURL = String.format(TASK_QUERY_STRING, baseUri,
      Constants.TEZ_TASK_ID, batchSize, Constants.TEZ_DAG_ID, dagId);
  downloadJSONArrayFromATS(taskURL, zos, Constants.TASKS);

  //Download task attempts
  String taskAttemptURL = String.format(TASK_ATTEMPT_QUERY_STRING, baseUri,
      Constants.TEZ_TASK_ATTEMPT_ID, batchSize, Constants.TEZ_DAG_ID, dagId);
  downloadJSONArrayFromATS(taskAttemptURL, zos, Constants.TASK_ATTEMPTS);
}
 
Example 17
Source File: ProjectSavingTask.java    From mzmine2 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Save the feature lists
 * 
 * @throws SAXException
 * @throws TransformerConfigurationException
 */
private void savePeakLists(ZipOutputStream zipStream)
    throws IOException, TransformerConfigurationException, SAXException {

  PeakList peakLists[] = savedProject.getPeakLists();

  for (int i = 0; i < peakLists.length; i++) {

    if (isCanceled())
      return;

    logger.info("Saving feature list: " + peakLists[i].getName());

    String peakListSavedName = "Peak list #" + (i + 1) + " " + peakLists[i].getName();

    zipStream.putNextEntry(new ZipEntry(peakListSavedName + ".xml"));

    peakListSaveHandler = new PeakListSaveHandler(zipStream, dataFilesIDMap);

    currentSavedObjectName = peakLists[i].getName();
    peakListSaveHandler.savePeakList(peakLists[i]);
    finishedSaveItems++;
  }
}
 
Example 18
Source File: WebArchives.java    From tomee with Apache License 2.0 4 votes vote down vote up
public static File warArchive(final Map<String, String> entries, final String archiveNamePrefix, final Class... classes) throws IOException {

        final ClassLoader loader = WebArchives.class.getClassLoader();

        File classpath;
        try {
            classpath = File.createTempFile(archiveNamePrefix, ".war");
        } catch (final Throwable e) {
            final File tmp = new File("tmp");
            if (!tmp.exists() && !tmp.mkdirs()) {
                throw new IOException("Failed to create local tmp directory: " + tmp.getAbsolutePath());
            }

            classpath = File.createTempFile(archiveNamePrefix, ".war", tmp);
        }

        // Create the ZIP file
        final ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(classpath)));

        for (final Class clazz : classes) {
            final String name = clazz.getName().replace('.', File.separatorChar) + ".class";

            final URL resource = loader.getResource(name);
            assertNotNull(resource);

            // Add ZIP entry to output stream.
            out.putNextEntry(new ZipEntry("WEB-INF/classes/" + name));

            final InputStream in = new BufferedInputStream(resource.openStream());

            int i;
            while ((i = in.read()) != -1) {
                out.write(i);
            }

            // Complete the entry
            in.close();
            out.closeEntry();
        }

        for (final Map.Entry<String, String> entry : entries.entrySet()) {

            out.putNextEntry(new ZipEntry(entry.getKey()));

            out.write(entry.getValue().getBytes());
        }

        // Complete the ZIP file
        out.close();
        return classpath;
    }
 
Example 19
Source File: ConfigGenerator.java    From FoxBPM with Apache License 2.0 4 votes vote down vote up
public void generate(ZipOutputStream out) {
	log.debug("开始处理 config...");
	try{
		String dirPath = "config";
		URL url = this.getClass().getClassLoader().getResource(dirPath);
		if(url == null){
			log.warn("config位置:" + dirPath + " 不存在,跳过不处理");
			return;
		}
		String urlStr = url.toString();
		String jarPath = urlStr.substring(0, urlStr.indexOf("!/") + 2);
		URL jarURL = new URL(jarPath);
		JarURLConnection jarCon = (JarURLConnection) jarURL.openConnection();
		JarFile jarFile = jarCon.getJarFile();
		
		Enumeration<JarEntry> jarEntrys = jarFile.entries();
		while (jarEntrys.hasMoreElements()) {
			JarEntry entry = jarEntrys.nextElement();
			// 简单的判断路径,如果想做到想Spring,Ant-Style格式的路径匹配需要用到正则。
			String name = entry.getName();
			if(name.startsWith(dirPath) && !entry.isDirectory() && !name.endsWith(".class")){
				int size = 1024;
				InputStream is = jarFile.getInputStream(entry);
				String tmpEntryName = "coreconfig/" + name.substring(dirPath.length()+1);
				ZipEntry zipEntry = new ZipEntry(tmpEntryName);
				zipEntry.setMethod(ZipEntry.DEFLATED);// 设置条目的压缩方式
				out.putNextEntry(zipEntry);
				int n = 0;
				byte b[] = new byte[size];
				while((n=is.read(b)) != -1){
					out.write(b , 0 , n);
				}
				out.closeEntry();
				is.close();
			}
		}
		log.debug("处理 config 完毕");
	}catch(Exception ex){
		log.error("转换config时出错",ex);
		throw new FoxBPMException("转换config时出错", ex);
	}
	
}
 
Example 20
Source File: SupportUtil.java    From syndesis with Apache License 2.0 4 votes vote down vote up
protected void addEntryToZip(String integrationName, InputStream fileContent, ZipOutputStream os) throws IOException {
    ZipEntry ze = new ZipEntry(integrationName + ".log");
    os.putNextEntry(ze);
    IOUtils.copy(fileContent, os);
    os.closeEntry();
}