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
java.util.zip - Recreating directory structure(转)的更多相关文章
- 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 ...
- java.util.zip.ZipException: invalid entry size 解决办法
启动maven项目时报java.util.zip.ZipException: invalid entry size (expected 7612 but got 5955 bytes) 可能是mave ...
- [Java 基础] 使用java.util.zip包压缩和解压缩文件
reference : http://www.open-open.com/lib/view/open1381641653833.html Java API中的import java.util.zip ...
- 启动TOMCAT报错 java.util.zip.ZipException: invalid LOC header (bad signature)
报错信息大致如下所示: at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect. ...
- java.util.zip.ZipOutputStream压缩无乱码(原创)
package io; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.FileI ...
- [java bug记录] java.util.zip.ZipException: invalid code lengths set
1. 描述:将代码迁移到maven工程,其中用ZipInputStream读取/src/main/resources下的zip文件时报错:“java.util.zip.ZipException: in ...
- java.util.zip压缩打包文件总结二: ZIP解压技术
一.简述 解压技术和压缩技术正好相反,解压技术要用到的类:由ZipInputStream通过read方法对数据解压,同时需要通过CheckedInputStream设置冗余校验码,如: Checked ...
- java.util.zip压缩打包文件总结一:压缩文件及文件下面的文件夹
一.简述 zip用于压缩和解压文件.使用到的类有:ZipEntry ZipOutputStream 二.具体实现代码 package com.joyplus.test; import java.io ...
- java.util.zip.GZIPInputStream.readUByte,Not in GZIP format错误处理
问题一: 使用webclient抓取网页时报错:(GZIPInputStream.java:207) atjava.util.zip.GZIPInputStream.readUShort(GZIPIn ...
随机推荐
- [转]SELinux管理与配置
原文链接:http://blog.csdn.net/huangbiao86/article/details/6641893 1.1 SElinux概述 SELinux(Security-Enhance ...
- java--方法和成员的继承,访问
//在调用方法的时候,不是看句柄是哪一个类,而应该看对象是属于哪一个类的,属于哪一个类的,就调用哪一个类的成员和方法. //子类可以添加自己的新方法,但是子类对象的引用赋值给父类句柄之后,不能使用父类 ...
- Qt 无边框窗体改变大小 完美实现
近期,做项目用到无边框窗体,令人蛋疼的是无边框窗体大小的改变要像右边框那样,上下左右四周,而且要流畅. 网上也找了些代码,发现居然还要连接到windows事件,这显然不合常理,后来自己新建了demo, ...
- Jquery学习笔记:通过层次关系获取jquery对象
前面一篇文章,我们介绍了如何通过web标签的id , css样式值来获取jquery对象. 但这只是基本方法,不能满足所有场景的需求. 本文介绍通过dom元素之间的层次关系获取元素.具体是将各种标识符 ...
- 在Myeclipse中安装java Decompiler
由于在myeclipse中的Help选项中没有Install New Software,所以在eclipse中安装插件的方法并不适应于Myeclipse,但是我们可以通过点击Windows->P ...
- VC实现URL编解码器
//变化UTF8为了中国 void UTF8ToGB(CString& szstr) { WCHAR* strSrc; TCHAR* szRes; int i = MultiByteToWid ...
- 利用内容提供者插入sms(装B程序)
1.sms的权限配置 <uses-permission android:name="android.permission.READ_SMS"/> <uses-pe ...
- 总线接口与计算机通信(五)CAN总线
CAN网络图示 CAN的特点 CAN协议具有以下特点. (1) 多主控制 在总线空闲时,所有的单元都可开始发送消息(多主控制). 最先访问总线的单元可获得发送权( ...
- EFM32在使用IAR开发环境配置ICf文件以及指定程序存储地址空间
EFM32在IAR开发环境下指定代码,数据的存储空间 为了便于后续的项目升级,管理,需要对代码,数据的存储空间加以设定,也在网上找下相关的资料,笔者水平有限, 如下内容不一定完全正确,如有错误之后,还 ...
- 使用C语言实现字符串中子字符串的替换
描述:编写一个字符串替换函数,如函数名为 StrReplace(char* strSrc, char* strFind, char* strReplace),strSrc为原字符串,strFind是待 ...