java.util.zip.ZipOutputStream#putNextEntry ( )源码实例Demo

下面列出了java.util.zip.ZipOutputStream#putNextEntry ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: carbon-apimgt   文件: ZIPUtils.java
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);
                }
            }
        }
    }
}
 
源代码2 项目: Compressor   文件: MyZip.java
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);
		}
	}
}
 
源代码3 项目: commons-vfs   文件: BaseFilterTest.java
/**
 * 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();
    }
}
 
源代码4 项目: DocBleach   文件: ArchiveBleach.java
@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);
  }
}
 
源代码5 项目: mars-sim   文件: CompressBitmap.java
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);
}
 
源代码6 项目: j2objc   文件: ZipEntryTest.java
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();
}
 
源代码7 项目: tomee   文件: ServiceClasspathTest.java
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;
}
 
源代码8 项目: ApiManager   文件: Tools.java
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();
                }
            }
        }
    }
}
 
源代码9 项目: xipki   文件: OcspCertstoreDbExporter.java
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();
}
 
源代码10 项目: fc-java-sdk   文件: ZipUtils.java
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();
}
 
源代码11 项目: JAADAS   文件: DexPrinter.java
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();
	}
}
 
源代码12 项目: metanome-algorithms   文件: LongBitSet.java
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();
}
 
源代码13 项目: jumbune   文件: Instrumenter.java
/**
 * <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);
}
 
源代码14 项目: screenshot-tests-for-android   文件: AlbumImpl.java
@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;
}
 
源代码15 项目: tmc-intellij   文件: RecursiveZipper.java
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();
}
 
源代码16 项目: syndesis   文件: SupportUtil.java
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();
}
 
源代码17 项目: FoxBPM   文件: ConfigGenerator.java
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);
	}
	
}
 
源代码18 项目: tez   文件: ATSImportTool.java
/**
 * 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);
}
 
源代码19 项目: tomee   文件: WebArchives.java
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;
    }
 
源代码20 项目: mzmine2   文件: ProjectSavingTask.java
/**
 * 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++;
  }
}