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. Javascript DOM 02 在<ul>中创建、删除 <li>

    创建DOM元素 createElement(标签名)  创建一个节点 appendChild(节点)  追加一个节点 例子:为ul插入li 插入元素 insertBefore(节点, 原有节点)  在 ...

  2. C--全排列的实现(递归方法) 傻子也能看懂的

      假设数组含有n个元素,则提取数组中的每一个元素做一次头元素,然后全排列除数组中除第一个元素之外的所有元素,这样就达到了对数组中所有元素进行全排列的得目的.[这句话才是重点!] 比如 1,2,3.的 ...

  3. html5新特性:利用history的pushState等方法来解决使用ajax导致页面后退和前进的问题

    一.背景 使用ajax,可以实现不需要刷新整个页面就可以进行局部页面的更新.这样可以开发交互性很强的富客户端程序,减少网络传输的内容.但长期以来存在一个问题,就是无法利用浏览器本身提供的前进和后退按钮 ...

  4. [置顶] ssize_t与size_t-linux

    ssize_t: signed size_t [注释:signed 有符号] size_t: 标准C库中定义的,应为unsigned int [注释:unsigned 无符号] 一.size_t 增强 ...

  5. GridView点击空白地方事件扩展

    我们通常在ListView或者GridView响应点击Item事件,但很多时候我们同样也 希望监听到点击空白区域的事件来做更多的处理.本文以GridView为例给出一个实现 的方法,扩展GridVie ...

  6. 数据结构读书笔记(三)(C语言)

    栈 顺序实现: 存储结构: #define STACK_INIT_SIZE 10 // 存储空间初始分配量 #define STACK_INCREMENT 2 // 存储空间分配增量 struct S ...

  7. ASP.NET 4.5 Bundle组件(捆绑、缩小静态文件)

    阅读目录: 1.开篇介绍 2.System.Web.Optimization 组件 3.System.Web.Optimization 组件基本原理 4.扩展自定义类型静态文件 1]开篇介绍 这篇文章 ...

  8. Qt5窗口设计

    主窗口设计通常是应用程序界面设计的第一步,主窗口主要分为窗口标题,菜单栏,工具栏和状态栏这四个部分,只要在程序设计中分别对四个项目进行设计就可以实现主窗口的编程了.在下面的例子中,我们就以一个打开文件 ...

  9. 基于visual Studio2013解决面试题之1305字符串所有子集

     题目

  10. windows下安装mysql5.6.13的主从复制

    如下操作均在vmware 虚拟机中winows xp 测试成功 中间走了很多弯路,网上的很多资料都是针对5.1以前的版本,在新版中根本无法使用,所以根据自己的实践整理了这篇文章 主服务:192.168 ...