Demo:
/**
* 2019年6月20日下午4:59:37
*/
package testzip;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
/**
* @author XWF
*
*/
public class TestZip {
/**
* @param args
*/
public static void main(String[] args) {
doZip();
doUnzip();
}
public static void doZip() {
try {
//定义生成压缩的文件
File zipf = new File("hello.zip");
if(!zipf.exists()) {
System.out.println("创建新zip文件结果:" + zipf.createNewFile());
}
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipf));
//需要压缩的文件
File infile = new File("testzip.txt");
FileInputStream fis = new FileInputStream(infile);
//设置zip文件里组织结构
zos.putNextEntry(new ZipEntry(infile.getName()));//压缩文件里直接用同名文件压缩
int len = 0;
byte[] b = new byte[1024];
while((len = fis.read(b)) > 0) {
zos.write(b, 0, len);
}
fis.close();
//在压缩文件里再保存一份testzip.txt的压缩,并换目录和名字
zos.putNextEntry(new ZipEntry("newFolder/a.txt"));//压缩文件里有一个叫newFolder的文件夹,里面保存testzip.txt的压缩,并用a.txt命名
fis = new FileInputStream(infile);
while((len = fis.read(b)) > 0) {
zos.write(b, 0, len);
}
zos.closeEntry();
zos.close();
fis.close();
System.out.println("压缩完成。");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void doUnzip() {
try {
File zipFile = new File("hello.zip");
ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry zipEntry = null;
while((zipEntry = zis.getNextEntry()) != null) {
System.out.println("zipEntry.getName:" + zipEntry.getName());
int index = zipEntry.getName().lastIndexOf("/");
String newFileName = zipEntry.getName().substring(index == -1?0:index+1);//去掉压缩包里的文件夹,这里只要文件名
File newFile = new File("unzip_"+newFileName);
FileOutputStream fos = new FileOutputStream(newFile);
int len = 0;
byte[] b = new byte[1024];
while((len = zis.read(b)) > 0) {
fos.write(b, 0, len);
fos.flush();
}
fos.close();
}
zis.closeEntry();
zis.close();
System.out.println("解压完成。");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
结果: