总结一下实现压缩文件的几个步骤:
1.创建压缩文件的对象(一旦创建对象,就会创建对应名称的压缩文件)
2.创建文件入口(这里传入的参数是压缩文件中的路径,可随意)
3.通过putNextEntry方法移动到入口上
4.进行你所需要的操作
5.关流
前三步是必须的,当然最后关流也是必须的
package com.baishiwei.myFileDemo;
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 MyZipDemo {
private void zip(String zipFileName, File inputFile) throws Exception {
// 创建zip对象
ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(new File(zipFileName)));
// 判断并输出
isDir(zipOutputStream, inputFile);
// 关流
zipOutputStream.close();
}
public void isDir(ZipOutputStream zipOutputStream, File file) throws IOException {
// 判断是否文件夹
if (file.isDirectory()) {
File[] listFiles = file.listFiles();
// 判断一下空文件夹的处理
if (listFiles.length == 0 || listFiles == null) {
String absolutePath = file.getAbsolutePath();
absolutePath = absolutePath.substring(absolutePath.indexOf("\\") + 1);
// 创建新的入口
ZipEntry zipEntry = new ZipEntry(absolutePath + "\\");
zipOutputStream.putNextEntry(zipEntry);
// 关闭入口
zipOutputStream.closeEntry();
}
for (File file2 : listFiles) {
isDir(zipOutputStream, file2);
}
} else {
// 将文件路径的盘符去掉
String absolutePath = file.getAbsolutePath();
absolutePath = absolutePath.substring(absolutePath.indexOf("\\") + 1);
// 设置入口
ZipEntry zipEntry = new ZipEntry(absolutePath);
// 移动到入口
zipOutputStream.putNextEntry(zipEntry);
// 读取打印文件
readFile(zipOutputStream, file);
}
}
public void readFile(ZipOutputStream zipOutputStream, File file) throws IOException {
// 输出
FileInputStream fileInputStream = new FileInputStream(file);
int length = -1;
byte[] b = new byte[1024];
while((length = fileInputStream.read(b)) != -1) {
zipOutputStream.write(b, 0, length);
}
fileInputStream.close();
}
public static void main(String[] temp) { // 主方法
try {
MyZipDemo myZipDemo = new MyZipDemo();
myZipDemo.zip("F:\\b.zip", new File("F:\\QMDownload"));
} catch (Exception e) {
e.printStackTrace();
}
}
}