java.util.zip - Recreating directory structure(转)

include my own version for your reference.
We use this one to zip up photos to download so it works with various unzip programs. It preserves the directory structure and timestamps.

public static void createZipFile(File srcDir, OutputStream out,
   boolean verbose) throws IOException {

  List<String> fileList = listDirectory(srcDir);
  ZipOutputStream zout = new ZipOutputStream(out);

  zout.setLevel(9);
  zout.setComment("Zipper v1.2");

  for (String fileName : fileList) {
   File file = new File(srcDir.getParent(), fileName);
   if (verbose)
    System.out.println("  adding: " + fileName);

   // Zip always use / as separator
   String zipName = fileName;
   if (File.separatorChar != ‘/‘)
    zipName = fileName.replace(File.separatorChar, ‘/‘);
   ZipEntry ze;
   if (file.isFile()) {
    ze = new ZipEntry(zipName);
    ze.setTime(file.lastModified());
    zout.putNextEntry(ze);
    FileInputStream fin = new FileInputStream(file);
    byte[] buffer = new byte[4096];
    for (int n; (n = fin.read(buffer)) > 0;)
     zout.write(buffer, 0, n);
    fin.close();
   } else {
    ze = new ZipEntry(zipName + ‘/‘);
    ze.setTime(file.lastModified());
    zout.putNextEntry(ze);
   }
  }
  zout.close();
 }

 public static List<String> listDirectory(File directory)
   throws IOException {

  Stack<String> stack = new Stack<String>();
  List<String> list = new ArrayList<String>();

  // If it‘s a file, just return itself
  if (directory.isFile()) {
   if (directory.canRead())
    list.add(directory.getName());
   return list;
  }

  // Traverse the directory in width-first manner, no-recursively
  String root = directory.getParent();
  stack.push(directory.getName());
  while (!stack.empty()) {
   String current = (String) stack.pop();
   File curDir = new File(root, current);
   String[] fileList = curDir.list();
   if (fileList != null) {
    for (String entry : fileList) {
     File f = new File(curDir, entry);
     if (f.isFile()) {
      if (f.canRead()) {
       list.add(current + File.separator + entry);
      } else {
       System.err.println("File " + f.getPath()
         + " is unreadable");
       throw new IOException("Can‘t read file: "
         + f.getPath());
      }
     } else if (f.isDirectory()) {
      list.add(current + File.separator + entry);
      stack.push(current + File.separator + f.getName());
     } else {
      throw new IOException("Unknown entry: " + f.getPath());
     }
    }
   }
  }
  return list;
 }
}

SEPARATOR constant is initialised with the System.getProperty("file.separator") which will give me the OS default file separator.
I would never hardcode a separator since that assumes that your code will only be deployed on a given OS

Don‘t use File.separator in ZIP. The separator must be "/" according to the spec. If you are on Windows, you must open file as "D:\dir\subdir\file" but ZIP entry must be "dir/subdir/file"

Just go through the source of java.util.zip.ZipEntry. It treats a ZipEntry as directory if its name ends with "/" characters. Just suffix the directory name with "/". Also you need to remove the drive prefix to make it relative.

Here is another example (recursive) which also lets you include/exclude the containing folder form the zip:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipUtil {

  private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;

  public static void main(String[] args) throws Exception {
    zipFile("C:/tmp/demo", "C:/tmp/demo.zip", true);
  }

  public static void zipFile(String fileToZip, String zipFile, boolean excludeContainingFolder)
    throws IOException {
    ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));    

    File srcFile = new File(fileToZip);
    if(excludeContainingFolder && srcFile.isDirectory()) {
      for(String fileName : srcFile.list()) {
        addToZip("", fileToZip + "/" + fileName, zipOut);
      }
    } else {
      addToZip("", fileToZip, zipOut);
    }

    zipOut.flush();
    zipOut.close();

    System.out.println("Successfully created " + zipFile);
  }

  private static void addToZip(String path, String srcFile, ZipOutputStream zipOut)
    throws IOException {
    File file = new File(srcFile);
    String filePath = "".equals(path) ? file.getName() : path + "/" + file.getName();
    if (file.isDirectory()) {
      for (String fileName : file.list()) {
        addToZip(filePath, srcFile + "/" + fileName, zipOut);
      }
    } else {
      zipOut.putNextEntry(new ZipEntry(filePath));
      FileInputStream in = new FileInputStream(srcFile);

      byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
      int len;
      while ((len = in.read(buffer)) != -1) {
        zipOut.write(buffer, 0, len);
      }

      in.close();
    }
  }
}

http://stackoverflow.com/questions/1399126/java-util-zip-recreating-directory-structure

时间: 2024-10-21 13:28:46

java.util.zip - Recreating directory structure(转)的相关文章

java.util.zip包在解压缩文件方面入门使用

工作空闲之余,无意间点了一下java.util.zip包下面的一些源码看了一看.知道其使用的范围就是针对我们日常中关于 文件的压缩和解压的操作.写了一些常用的压缩文件(单个文件和多个文件的压缩).解压文件(解压单个文件和文件夹)的 小小Demo. package com.clark.zip; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IO

java.util.zip.ZipException: error in opening zip file

今天项目升级,出现了很奇葩的问题.在本地和测试环境测试好好的,将项目打包成war(每次都这样打包)然后上传到阿里云服务器,启动tomcat一直报如下错误: java.util.zip.ZipException: error in opening zip file at java.util.zip.ZipFile.open(Native Method) at java.util.zip.ZipFile.<init>(ZipFile.java:220) at java.util.zip.ZipFi

java.util.zip.ZipOutputStream压缩无乱码(原创)

package io; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.zip.Adler32; import java.u

启动TOMCAT报错 java.util.zip.ZipException: invalid LOC header (bad signature)

报错信息大致如下所示: at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:303) at org.apache.catalina.startup.Bootstrap.main(Bootstr

java.util.zip压缩打包文件总结二: ZIP解压技术

一.简述 解压技术和压缩技术正好相反,解压技术要用到的类:由ZipInputStream通过read方法对数据解压,同时需要通过CheckedInputStream设置冗余校验码,如: CheckedInputStream cis = new CheckedInputStream(new FileInputStream( srcFile), new CRC32()); ZipInputStream zis = new ZipInputStream(cis); 需要注意的是,在构建解压文件时,需要

[java ] java.util.zip.ZipException: error in opening zip file

严重: Failed to processes JAR found at URL [jar:file:/D:/tools/apache-tomcat-7.0.64_2/webapps/bbs/WEB-INF/lib/org.restlet.ext.servlet-2.3.0.jar!/] for static resources to be included in context with name [jar:file:/D:/tools/apache-tomcat-7.0.64_2/webap

java架构 [Java 基础] 使用java.util.zip包压缩和解压缩文件

Java API中的import java.util.zip.*;包下包含了Java对于压缩文件的所有相关操作. 我们可以使用该包中的方法,结合IO中的相关知识,进行文件的压缩和解压缩相关操作. ZipFile java中的每一个压缩文件都是可以使用ZipFile来进行表示的. File file = new File("F:/zippath.zip"); ZipFile zipFile = new ZipFile(file); System.out.println("压缩文

[Java 基础] 使用java.util.zip包压缩和解压缩文件

reference :  http://www.open-open.com/lib/view/open1381641653833.html Java API中的import java.util.zip.*;包下包含了Java对于压缩文件的所有相关操作. 我们可以使用该包中的方法,结合IO中的相关知识,进行文件的压缩和解压缩相关操作. ZipFile java中的每一个压缩文件都是可以使用ZipFile来进行表示的. File file = new File("F:/zippath.zip&quo

java.util.zip

使用java自带的类 java.util.zip进行文件/目录的压缩的话,有一点不足,不支持中文的名件/目录命名,如果有中文名,那么打包就会失败.本人经过一段时间的摸索和实践,发现在一般的Ant.jar类库中也有zip类,import org.apache.tools.zip.*,能够解决不支持中文文件目录的问题,同时,Ant的获得途径也比较多,一般的应用服务器中有这个包,实在不行去下载个tomcat5.X,里面也有ant.jar,本人经过测试,可以使用. 例子如下: import java.i