62,628
社区成员
发帖
与我相关
我的任务
分享
/**
* 参数:传入需要压缩文件的绝对路径
*/
public static void compress(String sourcePath) {
try {
// 1. 创建一个压缩流、并且如果没有关联的压缩文件,自动创建 -- 压缩后的文件在桌面上
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("C:\\Users\\lrc\\Desktop\\压缩.zip"));
BufferedOutputStream bos = new BufferedOutputStream(zos);
// 2. 将即将压缩的文件名转为 File对象
File f = new File(sourcePath);
// 3. 调用递归函数
zipFile(zos, bos, f, f.getName());
// 4. 压缩输出流关闭
bos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void zipFile(ZipOutputStream zos, BufferedOutputStream bos, File f, String prefix) throws IOException {
// 1. 获取当前File对象 是文件 则返回null 是目录则返回File数组
File[] files = f.listFiles();
// 2. 文件压缩
if (files == null) {
zos.putNextEntry(new ZipEntry(prefix));
InputStream is = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(is);
byte[] buffer = new byte[2048];
int len = -1;
while ((len = bis.read()) != -1) {
bos.write(buffer, 0, len);
}
bis.close();
// 3. 空目录压缩
} else if(files.length == 0) {
zos.putNextEntry(new ZipEntry(prefix + "\\"));
// 4. 目录内各个文件的压缩
} else {
for (File file : files) {
zipFile(zos, bos, file, prefix + "\\" + file.getName());
}
}
}
