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

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

  1. Java.util.zip adding a new file overwrites entire jar?(转)

    ZIP and TAR fomats (and the old AR format) allow file append without a full rewrite. However: The Ja ...

  2. java.util.zip.ZipException: invalid entry size 解决办法

    启动maven项目时报java.util.zip.ZipException: invalid entry size (expected 7612 but got 5955 bytes) 可能是mave ...

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

    reference :  http://www.open-open.com/lib/view/open1381641653833.html Java API中的import java.util.zip ...

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

    报错信息大致如下所示: at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect. ...

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

    package io; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.FileI ...

  6. [java bug记录] java.util.zip.ZipException: invalid code lengths set

    1. 描述:将代码迁移到maven工程,其中用ZipInputStream读取/src/main/resources下的zip文件时报错:“java.util.zip.ZipException: in ...

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

    一.简述 解压技术和压缩技术正好相反,解压技术要用到的类:由ZipInputStream通过read方法对数据解压,同时需要通过CheckedInputStream设置冗余校验码,如: Checked ...

  8. java.util.zip压缩打包文件总结一:压缩文件及文件下面的文件夹

    一.简述 zip用于压缩和解压文件.使用到的类有:ZipEntry  ZipOutputStream 二.具体实现代码 package com.joyplus.test; import java.io ...

  9. java.util.zip.GZIPInputStream.readUByte,Not in GZIP format错误处理

    问题一: 使用webclient抓取网页时报错:(GZIPInputStream.java:207) atjava.util.zip.GZIPInputStream.readUShort(GZIPIn ...

随机推荐

  1. [转]CentOS下性能监测工具 dstat

    原文链接:http://www.bkjia.com/Linuxjc/935113.html 参考链接:https://linux.cn/article-3215-1.html,http://lhfli ...

  2. jackson 转json. 过滤null值

    @Test public void tttttt() throws JsonGenerationException, JsonMappingException, IOException { Objec ...

  3. 阿里云ECS专有网络产品三个步骤配置教程

    阿里云ECS专有网络产品三个步骤配置教程 阿里云专有网络节点已开通地域:美国硅谷可用区1B,新加坡可用区A,北京可用区A,深圳可用区A,杭州可用区D,上海可用区B 举个栗子:购买 美国硅谷可用区1B  ...

  4. NOI2007 生成树计数

    题目 首先我要吐槽,这题目就是坑,给那么多无用的信息,我还以为要根据提示才能做出来呢! 算法1 暴力,傻傻地跟着提示,纯暴力\(40\)分,高斯消元\(60\)分. 算法2 DP!一个显然的东西是,这 ...

  5. hdu 2546 饭卡 01背包

    先将前n-1个从小到大排序.对m-5进行01背包.然后答案就是m-dp[m-5]-a[n-1] 至于为什么最后减去最贵的菜品,而不是把最贵的菜品也放到01背包里呢, 由于假设能够把最贵菜品a[n-1] ...

  6. RedHat Linux 5.5安装JDK+Tomcat并部署Java项目

    与大家分享下RedHat Linux 5.5安装JDK+Tomcat并部署Java项目的步骤,希望对大家有用. 1.下载并安装jdk 虚拟机中安装RedHat Linux 5.5 64位企业版, 这里 ...

  7. Tomcat 7最大并发连接数的正确修改方法(转)

    几乎所有的中文网页都介绍,要修改Tomcat的默认最大并发连接数,应该进行如下设置(实际上这些步骤是错误的): -------------------------------------------- ...

  8. 基于visual Studio2013解决C语言竞赛题之1047百马问题

      题目 解决代码及点评 /* 47.马百瓦问题.有100匹马,100块瓦,大马驮3块, 小马驮2块,两个马驹驮1块.问大马.小马.马驹各多少? 要求:① 不许用for循环; ② 循环次数 ...

  9. Cocos2d-x教程(30)-3.x版本号物理引擎的使用

    转载时请注明原文出处 : http://blog.csdn.net/u012945598/article/details/38417333 在Cocos2d-x 2.x的版本号中,开发人员能够直接使用 ...

  10. 基于visual Studio2013解决面试题之0409判断一个栈是否另外一个栈的弹出序列

     题目