package com.wxz;
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* TODO
*
* @author wxz
* @date 2021/9/30 15:21
*/
public class Test {
/**
* @Description:
* @param srcPath 要压缩的文件路径
* @param dstPath 压缩后的zip路径
* @return void
* @author wxz
* @date 2021/11/16 11:41
*/
public static void compress(String srcPath , String dstPath) throws IOException{
File srcFile = new File(srcPath);
File dstFile = new File(dstPath);
if (!srcFile.exists()) {
throw new FileNotFoundException(srcPath + "不存在!");
}
ZipOutputStream zipOut = null;
try {
zipOut = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(dstFile)));
String baseDir = "";
compressPro(srcFile, zipOut, baseDir);
}
finally {
if(null != zipOut){
zipOut.close();
}
}
}
private static void compressPro(File srcFile, ZipOutputStream zipOut,String baseDir) throws IOException{
if (srcFile.isDirectory()) {
compressDirectory(srcFile,zipOut,baseDir);
} else {
compressFile(srcFile,zipOut,baseDir);
}
}
/** 压缩一个目录 */
private static void compressDirectory(File dir, ZipOutputStream zipOut,String baseDir) throws IOException{
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
compressPro(files[i], zipOut, baseDir + dir.getName() + "/");
}
}
/** 压缩一个文件 */
private static void compressFile(File file, ZipOutputStream zipOut,String baseDir) throws IOException{
if (!file.exists()){
return;
}
BufferedInputStream bis = null;
try {
bis = new BufferedInputStream(new FileInputStream(file));
zipOut.putNextEntry(new ZipEntry(baseDir + file.getName()));
int len;
byte bytes[] = new byte[1024];
while ((len = bis.read()) != -1) {
zipOut.write(bytes, 0, len);
}
}finally {
if(null != bis){
bis.close();
}
}
}
public static void main(String[] args) throws IOException {
// File file = new File("D:\\aly");
// File zipFile = new File("D:\\aly.zip");
// FileInputStream fis = new FileInputStream(file);
// ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
// byte[] bytes = new byte[1024];
// zipOutputStream.putNextEntry(new ZipEntry(file.getName()));
// int lenth;
// while((lenth=fis.read())!=-1){
// zipOutputStream.write(bytes,0,lenth);
// }
// zipOutputStream.close();
// fis.close();
String targetFolderPath = "D:\\hello.txt";
String newZipFilePath = "D:\\Dev\\wxz.zip";
//将目标目录的文件压缩成Zip文件
new Test().compress(targetFolderPath , newZipFilePath);
}
}
JAVA中压缩文件成zip
最新推荐文章于 2024-06-16 09:46:17 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)