java实现文件的压缩功能
程序员文章站
2022-05-07 17:25:32
...
package com.zl.myzip;
import java.io.File;
import java.io.IOException;
/**
*
* @author 丢了风筝的线
* @see 测试字符自定义文件的压缩
*/
public class TestMyZip {
public static void main(String[] args) {
MyZip myZip = new MyZip();
try {
myZip.zip("C:\\Users\\Administrator\\Desktop\\hello.zip",
new File("D:\\新建文件夹\\20191014优就业\\Java\\JavaSECode\\ZIPfile"));
System.out.println("压缩完成");
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.zl.myzip;
import java.io.BufferedInputStream;
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;
/**
*
* @author 丢了风筝的线
* @see 压缩文件
*/
public class MyZip {
public void zip(String zipFileName, File inputFileNme) throws IOException {
ZipOutputStream outputStream = new ZipOutputStream(new FileOutputStream(zipFileName));
zip(outputStream, inputFileNme, "");
System.out.println("正在压缩中");
outputStream.finish();
}
private void zip(ZipOutputStream out, File f, String base) throws IOException {
// 判断当前文件对象是否是文件夹
if (f.isDirectory()) {
// 获取当前目录的下一级所有文件对象(包括文件夹对象)
File[] fs = f.listFiles();
// 判断当前文件夹是否有下级内容
if (fs.length != 0) {
if (base.length() != 0) {
// 创建目录进入点,并将录入位置移动到目录进入点
out.putNextEntry(new ZipEntry(base + "/"));
}
// 循环遍历每一层
for (int i = 0; i < fs.length; i++) {
zip(out, fs[i], base + fs[i]);
}
}
} else {
// 创建文件目录进入点,并将录入点移动到该目录进入点
out.putNextEntry(new ZipEntry(base));
// 输入文件到程序
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(f));
int len;
byte[] flush = new byte[1024];
while ((len = bufferedInputStream.read()) != -1) {
out.write(flush);
}
bufferedInputStream.close();
}
}
}