0. 简介
- 简单的生成和读取 zip 文件
package com.willhonor.test;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import org.junit.Test;
public class Test_1 {
@Test
public void test_generateZipFile() throws Exception {
String zipFile = "E:\\temp\\temp\\docs.zip";
File file = new File(zipFile);
if (file.exists()) {
file.delete();
}
file.createNewFile();
ZipOutputStream zipOutputStream
= new ZipOutputStream(new FileOutputStream(file), UTF_8);
zipOutputStream.setComment("this is zip file, just for test.");
byte[] f1 = "hello this world, I'm here now, so happy!".getBytes(UTF_8);
addEntry(zipOutputStream, "hello.txt", f1);
byte[] f2 = "<p>这是我最喜欢的 blog 网站了</p>".getBytes(UTF_8);
addEntry(zipOutputStream, "我的书签收藏.html", f2);
addEntry(zipOutputStream, "others\\", null);
addEntry(zipOutputStream, "其它\\", null);
addEntry(zipOutputStream, "com\\", null);
addEntry(zipOutputStream, "com\\will\\", null);
addEntry(zipOutputStream, "com\\will\\honor\\", null);
byte[] f3 = "/** this is java source */".getBytes(UTF_8);
addEntry(zipOutputStream, "com/will/honor/test.java", f3);
zipOutputStream.close();
}
private void addEntry(ZipOutputStream os, String entityName, byte[] bytes) {
try {
ZipEntry entry = new ZipEntry(entityName);
os.putNextEntry(entry);
if (bytes != null && bytes.length > 0) {
os.write(bytes);
}
os.closeEntry();
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void test_useZipFileClass() throws Exception {
String fileName = "E:\\temp\\temp\\docs.zip";
ZipFile zipFile = new ZipFile(new File(fileName), UTF_8);
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while(entries.hasMoreElements()) {
ZipEntry en = entries.nextElement();
System.out.println(String.format("[%s]", new Object[] {en.getName()}));
if (!en.isDirectory()) {
InputStream is = zipFile.getInputStream(en);
byte[] bytes = getAllBytes(is);
System.out.println(new String(bytes, UTF_8) + "\n---------------");
}
}
zipFile.close();
}
public byte[] getAllBytes(InputStream is) {
if (is != null) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
int bufSize = 1024;
byte[] buf = new byte[bufSize];
int res = 0;
try {
while((res = is.read(buf)) > 0) {
out.write(buf, 0, res);
}
} catch (IOException e) {
e.printStackTrace();
}
return out.toByteArray();
}
return null;
}
@Test
public void test_useDifferentCharset() throws Exception {
String fileName = "E:\\temp\\temp\\usediffcharset.zip";
File file = new File(fileName);
if (file.exists()) {
file.delete();
}
file.createNewFile();
ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(file), UTF_8);
zipOutputStream.putNextEntry(new ZipEntry("Java编程实战.txt"));
zipOutputStream.write("这是Java编程实战,这是注释".getBytes(Charset.forName("gbk")));
zipOutputStream.close();
}
}
- 压缩指定的目录或文件(zipEntry 名称和 comment 使用 utf-8 编码,zipEntry 内容保持不变,即不对 zipEntry 内容重新解码和编码)
package com.willhonor.test;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.junit.Test;
public class Test_2 {
public static final String FILE_SYSTEM_SEPARATOR = FileSystems.getDefault().getSeparator();
public static void main(String[] args) {
String path = "E:\\360Downloads\\Software";
String zipFileName = "E:\\360Downloads\\";
doZip(path, zipFileName);
}
public static void doZip(String filePath, String zipFileName) {
if (filePath != null) {
Path path = Paths.get(filePath, new String[] {});
if (Files.notExists(path, new LinkOption[] {LinkOption.NOFOLLOW_LINKS})) {
System.out.println("指定路径不存在,path:" + path.toString());
System.out.println("程序退出");
System.exit(1);
}
Path parentPath = path.getParent();
final int parentPathLen = parentPath.toString().length();
zipFileName = getZipFileName(path, zipFileName);
File zipFile = createZipFileIfNotExist(zipFileName);
try {
final ZipOutputStream os = new ZipOutputStream(new FileOutputStream(zipFile), UTF_8);
if (Files.isDirectory(path, new LinkOption[] {LinkOption.NOFOLLOW_LINKS})) {
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException {
os.putNextEntry(new ZipEntry(dir.toString()
.substring(parentPathLen + FILE_SYSTEM_SEPARATOR.length())
+ FILE_SYSTEM_SEPARATOR));
os.closeEntry();
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
os.putNextEntry(new ZipEntry(path.toString()
.substring(parentPathLen + FILE_SYSTEM_SEPARATOR.length())));
os.write(Files.readAllBytes(path));
os.closeEntry();
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
});
}else {
os.putNextEntry(new ZipEntry(path.toString()
.substring(parentPathLen + FILE_SYSTEM_SEPARATOR.length())));
os.write(Files.readAllBytes(path));
os.closeEntry();
}
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static String getZipFileName(Path path, String zipFileName) {
String fileName = path.getFileName().toString();
if (zipFileName == null) {
Path parenPath = path.getParent();
zipFileName = parenPath.toString() + FILE_SYSTEM_SEPARATOR + fileName + ".zip";
} else {
if (zipFileName.endsWith(FILE_SYSTEM_SEPARATOR)) {
zipFileName += fileName;
}
if (!zipFileName.endsWith(".zip")) {
zipFileName += ".zip";
}
}
return zipFileName;
}
private static File createZipFileIfNotExist(String zipFileName) {
File file = new File(zipFileName);
if (!file.exists()) {
File parentFile = file.getParentFile();
if (parentFile != null && !parentFile.exists()) {
parentFile.mkdirs();
}
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}
}