org.apache.tools.zip.ZipOutputStream类的使用及代码示例

x33g5p2x  于2022-02-05 转载在 其他  
字(11.3k)|赞(0)|评价(0)|浏览(377)

本文整理了Java中org.apache.tools.zip.ZipOutputStream类的一些代码示例,展示了ZipOutputStream类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ZipOutputStream类的具体详情如下:
包路径:org.apache.tools.zip.ZipOutputStream
类名称:ZipOutputStream

ZipOutputStream介绍

[英]Reimplementation of java.util.zip.ZipOutputStream that does handle the extended functionality of this package, especially internal/external file attributes and extra fields with different layouts for local file data and central directory entries.

This class will try to use java.io.RandomAccessFile when you know that the output is going to go to a file.

If RandomAccessFile cannot be used, this implementation will use a Data Descriptor to store size and CRC information for #DEFLATED entries, this means, you don't need to calculate them yourself. Unfortunately this is not possible for the #STORED method, here setting the CRC and uncompressed size information is required before #putNextEntry can be called.

As of Apache Ant 1.9.0 it transparently supports Zip64 extensions and thus individual entries and archives larger than 4 GB or with more than 65536 entries in most cases but explicit control is provided via #setUseZip64. If the stream can not user RandomAccessFile and you try to write a ZipEntry of unknown size then Zip64 extensions will be disabled by default.
[中]java的重新实现。util。拉链ZipOutputStream,它可以处理这个包的扩展功能,尤其是内部/外部文件属性,以及本地文件数据和中心目录条目的不同布局的额外字段。
这个类将尝试使用java。伊奥。RandomAccessFile当您知道输出将进入文件时。
如果无法使用RandomAccessFile,此实现将使用数据描述符存储#DEFLATED条目的大小和CRC信息,这意味着您不需要自己计算它们。不幸的是,对于#存储方法,这是不可能的,在调用#putNextEntry之前,需要设置CRC和未压缩的大小信息。
从Apache Ant 1.9.0开始,它透明地支持Zip64扩展,因此单个条目和归档大于4 GB,或者在大多数情况下超过65536个条目,但通过#setUseZip64提供显式控制。如果流无法使用RandomAccessFile,并且您尝试写入未知大小的ZipEntry,则默认情况下将禁用Zip64扩展名。

代码示例

代码示例来源:origin: jenkinsci/jenkins

private static void zip(StaplerResponse rsp, VirtualFile root, VirtualFile dir, String glob) throws IOException, InterruptedException {
  OutputStream outputStream = rsp.getOutputStream();
  try (ZipOutputStream zos = new ZipOutputStream(outputStream)) {
    zos.setEncoding(System.getProperty("file.encoding")); // TODO JENKINS-20663 make this overridable via query parameter
        ZipEntry e = new ZipEntry(relativePath.replace('\\', '/'));
        VirtualFile f = dir.child(n);
        e.setTime(f.lastModified());
        zos.putNextEntry(e);
        try (InputStream in = f.open()) {
          IOUtils.copy(in, zos);
        zos.closeEntry();

代码示例来源:origin: jenkinsci/jenkins

public void close() throws IOException {
  zip.close();
}

代码示例来源:origin: jenkinsci/jenkins

ZipEntry dirZipEntry = new ZipEntry(relativePath+'/');
  dirZipEntry.setExternalAttributes(BITMASK_IS_DIRECTORY);
  if (mode!=-1)   dirZipEntry.setUnixMode(mode);
  dirZipEntry.setTime(f.lastModified());
  zip.putNextEntry(dirZipEntry);
  zip.closeEntry();
} else {
  ZipEntry fileZipEntry = new ZipEntry(relativePath);
  if (mode!=-1)   fileZipEntry.setUnixMode(mode);
  fileZipEntry.setTime(f.lastModified());
  zip.putNextEntry(fileZipEntry);
  try (InputStream in = Files.newInputStream(f.toPath())) {
    int len;
    while((len=in.read(buf))>=0)
      zip.write(buf,0,len);
  } catch (InvalidPathException e) {
    throw new IOException(e);
  zip.closeEntry();

代码示例来源:origin: jenkinsci/jenkins

ZipArchiver(OutputStream out) {
  zip = new ZipOutputStream(out);
  zip.setEncoding(System.getProperty("file.encoding"));
  zip.setUseZip64(Zip64Mode.AsNeeded);
}

代码示例来源:origin: org.apache.ant/ant

/**
 * Writes all necessary data for this entry.
 *
 * @since 1.1
 * @throws IOException on error
 * @throws Zip64RequiredException if the entry's uncompressed or
 * compressed size exceeds 4 GByte and {@link #setUseZip64}
 * is {@link Zip64Mode#Never}.
 */
public void closeEntry() throws IOException {
  preClose();
  flushDeflater();
  final Zip64Mode effectiveMode = getEffectiveZip64Mode(entry.entry);
  long bytesWritten = written - entry.dataStart;
  long realCrc = crc.getValue();
  crc.reset();
  final boolean actuallyNeedsZip64 =
    handleSizesAndCrc(bytesWritten, realCrc, effectiveMode);
  closeEntry(actuallyNeedsZip64);
}

代码示例来源:origin: gradle.plugin.com.bettycc.umengauto/core

private static void writePack(Map<ZipEntry, byte[]> readZipAllEntry, ZipFile file, String path, String channel)
    throws Exception {
  ZipOutputStream zot = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(path)));
  Iterator<ZipEntry> iterator = readZipAllEntry.keySet().iterator();
  while (iterator.hasNext()) {
    ZipEntry entry = iterator.next();
    zot.putNextEntry(entry);
    byte[] data = readZipAllEntry.get(entry);
    zot.write(data, 0, data.length);
    // System.out.println(entry);
    // System.out.println(entry.getSize() + " ," +
    // entry.getCompressedSize() + "," + data.length);
    zot.closeEntry();
  }
  zot.putNextEntry(new ZipEntry("META-INF/channel_" + channel));
  zot.closeEntry();
  zot.close();
}

代码示例来源:origin: org.jvnet.hudson.main/hudson-core

public void visit(File f, String relativePath) throws IOException {
  if(f.isDirectory()) {
    ZipEntry dirZipEntry = new ZipEntry(relativePath+'/');
    // Setting this bit explicitly is needed by some unzipping applications (see HUDSON-3294).
    dirZipEntry.setExternalAttributes(BITMASK_IS_DIRECTORY);
    zip.putNextEntry(dirZipEntry);
    zip.closeEntry();
  } else {
    zip.putNextEntry(new ZipEntry(relativePath));
    FileInputStream in = new FileInputStream(f);
    int len;
    while((len=in.read(buf))>0)
      zip.write(buf,0,len);
    in.close();
    zip.closeEntry();
  }
  entriesWritten++;
}

代码示例来源:origin: com.github.javahaohao/utils

if (folderObject.exists()) {
  ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(
      objFileName));
  zos.setEncoding("GBK");
  ZipEntry ze = null;
  int readLen = 0;
  if (null != file) {// 指定了某个文件
    zos.putNextEntry(ze);
    InputStream is = new BufferedInputStream(new FileInputStream(
        file));
    while ((readLen = is.read(buf, 0, 1024)) != -1)
      zos.write(buf, 0, readLen);
    is.close();
  } else {
      zos.putNextEntry(ze);
      InputStream is = new BufferedInputStream(
          new FileInputStream(f));
      while ((readLen = is.read(buf, 0, 1024)) != -1)
        zos.write(buf, 0, readLen);
      is.close();
  zos.close();
} else
  throw new Exception("this folder isnot exist!");

代码示例来源:origin: org.apache.ant/ant

final ZipEntry ze = new ZipEntry(vPath);
ze.setTime(fixedModTime != null ? modTimeMillis : lastModified);
ze.setMethod(doCompress ? ZipEntry.DEFLATED : ZipEntry.STORED);
if (!zOut.isSeekable() && !doCompress) {
  long size = 0;
  final CRC32 cal = new CRC32();
zOut.putNextEntry(ze);
do {
  if (count != 0) {
    zOut.write(buffer, 0, count);

代码示例来源:origin: hyperic/hq

zip_out = new ZipOutputStream(new BufferedOutputStream(file_out));
zip_out.setLevel(Deflater.BEST_COMPRESSION);
zip_out.setMethod(Deflater.DEFLATED);
  outEntry = new org.apache.tools.zip.ZipEntry(inEntry);
  outEntry.setMethod(Deflater.DEFLATED);
  if (!didReplacement && 
    matches(outEntry.getName(), pathToReplace)) {
    zip_out.putNextEntry(outEntry);
    FileUtil.copyStream(zip_in, zip_out, buf);
    zip_out.closeEntry();
zip_out.flush();
completedOK = true;

代码示例来源:origin: org.gradle/gradle-core

private void visitDir(FileCopyDetails dirDetails) {
    try {
      // Trailing slash in name indicates that entry is a directory
      ZipEntry archiveEntry = new ZipEntry(dirDetails.getRelativePath().getPathString() + '/');
      archiveEntry.setTime(getArchiveTimeFor(dirDetails));
      archiveEntry.setUnixMode(UnixStat.DIR_FLAG | dirDetails.getMode());
      zipOutStr.putNextEntry(archiveEntry);
      zipOutStr.closeEntry();
    } catch (Exception e) {
      throw new GradleException(String.format("Could not add %s to ZIP '%s'.", dirDetails, zipFile), e);
    }
  }
}

代码示例来源:origin: sanluan/PublicCMS

/**
 * @param file
 * @param out
 * @param basedir
 * @throws IOException
 */
private static void compress(Path sourceFilePath, ZipOutputStream out, String basedir) throws IOException {
  if (Files.isDirectory(sourceFilePath)) {
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(sourceFilePath);) {
      for (Path entry : stream) {
        BasicFileAttributes attrs = Files.readAttributes(entry, BasicFileAttributes.class);
        String fullName = Constants.BLANK.equals(basedir) ? entry.toFile().getName()
            : basedir + Constants.SEPARATOR + entry.toFile().getName();
        if (attrs.isDirectory()) {
          ZipEntry zipEntry = new ZipEntry(fullName + Constants.SEPARATOR);
          out.putNextEntry(zipEntry);
          compress(entry, out, fullName);
        } else {
          compressFile(entry.toFile(), out, fullName);
        }
      }
    } catch (IOException e) {
    }
  } else {
    compressFile(sourceFilePath.toFile(), out, sourceFilePath.toFile().getName());
  }
}

代码示例来源:origin: sanluan/PublicCMS

/**
 * @param sourceFilePath
 * @param zipFilePath
 * @param overwrite
 * @return whether the compression is successful
 * @throws IOException
 */
public static boolean zip(String sourceFilePath, String zipFilePath, boolean overwrite) throws IOException {
  if (CommonUtils.notEmpty(sourceFilePath)) {
    File zipFile = new File(zipFilePath);
    if (zipFile.exists() && !overwrite) {
      return false;
    } else {
      zipFile.getParentFile().mkdirs();
      try (FileOutputStream outputStream = new FileOutputStream(zipFile);
          ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
          FileLock fileLock = outputStream.getChannel().tryLock();) {
        if (null != fileLock) {
          zipOutputStream.setEncoding(Constants.DEFAULT_CHARSET_NAME);
          compress(Paths.get(sourceFilePath), zipOutputStream, Constants.BLANK);
          return true;
        }
      }
    }
  }
  return false;
}

代码示例来源:origin: apache/hive

public static void zip(String parentDir, String[] inputFiles, String outputFile)
  throws IOException {
 ZipOutputStream output = null;
 try {
  output = new ZipOutputStream(new FileOutputStream(new File(parentDir, outputFile)));
  for (int i = 0; i < inputFiles.length; i++) {
   File f = new File(parentDir, inputFiles[i]);
   FileInputStream input = new FileInputStream(f);
   output.putNextEntry(new ZipEntry(inputFiles[i]));
   try {
    IOUtils.copy(input, output);
   } finally {
    input.close();
   }
  }
 } finally {
  org.apache.hadoop.io.IOUtils.closeStream(output);
 }
}

代码示例来源:origin: com.github.javahaohao/utils

ZipEntry zipe = new ZipEntry(oppositePath + srcFile.getName());
try {
  zipOut.setEncoding("GBK");
  zipOut.putNextEntry(zipe);
  FileInputStream fileIn = new FileInputStream(srcFile);
  while ((readedBytes = fileIn.read(buf)) > 0) {
    zipOut.write(buf, 0, readedBytes);
  zipOut.flush();
  fileIn.close();
  zipOut.closeEntry();
} catch (Exception e) {
  System.out.println(e);

代码示例来源:origin: com.github.tianjing/tgtools.core

private static ZipOutputStream createZipOutputStream(OutputStream p_OutputSteam,String p_Comment)
{
  CheckedOutputStream csum = new CheckedOutputStream(p_OutputSteam,
      new CRC32());
  ZipOutputStream zos = new ZipOutputStream(csum);
  // 支持中文
  zos.setEncoding("GBK");
  // 设置压缩包注释
  zos.setComment(p_Comment);
  // 启用压缩
  zos.setMethod(ZipOutputStream.DEFLATED);
  // 压缩级别为最强压缩,但时间要花得多一点
  zos.setLevel(Deflater.BEST_COMPRESSION);
  return zos;
}

代码示例来源:origin: org.jvnet.hudson.plugins/cvs

zos.putNextEntry(new ZipEntry(name));
FileInputStream fis = new FileInputStream(f);
Util.copyStream(fis, zos);
fis.close();
zos.closeEntry();

代码示例来源:origin: sanluan/PublicCMS

/**
 * @param file
 * @param out
 * @param basedir
 * @throws IOException
 */
private static void compressFile(File file, ZipOutputStream out, String fullName) throws IOException {
  if (CommonUtils.notEmpty(file)) {
    ZipEntry entry = new ZipEntry(fullName);
    entry.setTime(file.lastModified());
    out.putNextEntry(entry);
    try (FileInputStream fis = new FileInputStream(file);) {
      StreamUtils.copy(fis, out);
    }
  }
}

代码示例来源:origin: com.github.javahaohao/utils

public static boolean doZip(String srcStr, String targetStr, String targetName) {
  File zipDir = new File(srcStr);
  // 未指定压缩文件名,默认为"ZipFile"
  if (StringUtils.isBlank(targetName))
    targetName = "ZipFile";
  // 添加".zip"后缀
  if (!targetName.endsWith(".zip"))
    targetName += ".zip";
  try {
    zipOut = new ZipOutputStream(new FileOutputStream(new File(targetStr + File.separator + targetName)));
    // 压缩文件
    compressFile(zipDir, "", zipOut);
    zipOut.close();
  } catch (IOException e) {
    flag = false;
    e.printStackTrace();
  }
  return flag;
}
/**

代码示例来源:origin: com.github.javahaohao/utils

if (file.isDirectory()) {
  fileName = fileName + "/";
  ZipEntry entry = new ZipEntry(fileName);
  entry.setTime(file.lastModified());
  zipOutput.putNextEntry(entry);
  String fileNames[] = file.list();
  if (ObjectUtils.isNotEmpty(fileNames)) {
  ZipEntry jarEntry = new ZipEntry(fileName);
  BufferedInputStream in = new BufferedInputStream(
      new FileInputStream(file));
  zipOutput.putNextEntry(jarEntry);
    zipOutput.write(buf, 0, len);
  in.close();

相关文章