java的zip的简单实例, 主要理解zip的两个类(ZipOutputStream ,ZipEntry ),看它如何进行压缩文件的
package com.student.zip;
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class MainZip {
public static void main(String[] args) {
File[] files = new File[]{new File("G:\\myWorkSpace\\myweb1111\\web\\download\\1.jpg"),
new File("G:\\myWorkSpace\\myweb1111\\web\\download\\2.jpg")};
File file = new File("G:\\myWorkSpace\\myweb1111\\web\\download\\new.zip");
pressZip(files, file);
}
private static void pressZip(File[] files, File file) {
// 文件是否存在,不存在就创建一个
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
OutputStream ous = null;
FileInputStream ios = null;
// zip用到zip的两个类 ZipOutputStream是文件输出类 ZipEntry定义是那些文件
ZipOutputStream zipOutputStream = null;
// 创建ZipEntry This class is used to represent a ZIP file entry.
ZipEntry zipEntry = null;
try {
ous = new FileOutputStream(file);
zipOutputStream = new ZipOutputStream(ous);
for (int i = 0; i < files.length; i++) {
ios = new FileInputStream(files[i]);
zipEntry = new ZipEntry(files[i].getName());
zipOutputStream.putNextEntry(zipEntry);
int len;
// 定义每次读取的字节数组
byte[] buffer = new byte[1024];
while ((len = ios.read(buffer)) > 0) {
zipOutputStream.write(buffer, 0, len);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (zipOutputStream!=null){
try {
zipOutputStream.closeEntry();
zipOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (ous!=null){
try {
ous.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (ios!=null){
try {
ios.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}