用io流简单实现了一个压缩文件的工具类。
package com.gzh.zip;
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* TODO
*
* @author DELL
* @version 1.0
* @since 2022-07-14 10:32:46
*/
public class ZipFiles {
public static void sourceToZip(String sourcePath,String targetPath) throws IOException {
File sourceFile = new File(sourcePath);
File targetFile = new File(targetPath);
if(!sourceFile.exists()) throw new RuntimeException("目标文件不存在");
if(!targetFile.isDirectory()) throw new RuntimeException("目标路径不是一个文件夹");
File targetZipFile = null;
if(!sourceFile.isDirectory()){
targetZipFile = new File(targetPath + sourceFile.getName().substring(0, sourceFile.getName().indexOf(".")) + ".zip");
}else {
targetZipFile = new File(targetPath + sourceFile.getName() + ".zip");
}
File[] file = sourceFile.listFiles();
ZipOutputStream zip = null;
try{
zip = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(targetZipFile)));
if(sourceFile.isFile()){
toZip(sourceFile,zip,"");
}else {
fileToZip(sourceFile, zip,"");
}
}catch (IOException e){
e.printStackTrace();
}finally {
zip.close();
}
}
//文件压缩
private static void toZip(File file,ZipOutputStream zip,String targetPath) throws IOException {
ZipEntry zipEntry = new ZipEntry(targetPath + file.getName());
byte[] bytes = new byte[1024];
zip.putNextEntry(zipEntry);
InputStream read = new FileInputStream(file);
int ch = -1;
while((ch = read.read(bytes)) != -1){
zip.write(bytes, 0, ch);
}
read.close();
zip.closeEntry();
}
//文件夹压缩
private static void fileToZip(File file,ZipOutputStream zip,String targetPath) throws IOException {
targetPath += file.getName() + File.separator;
ZipEntry entry = new ZipEntry(targetPath);
zip.putNextEntry(entry);
zip.closeEntry();
if(file.listFiles() == null || file.listFiles().length == 0) return;
File[] fileLists = file.listFiles();
for(File file1 : fileLists){
if(!file1.isDirectory()){
toZip(file1,zip,targetPath);
}else {
fileToZip(file1,zip,targetPath);
}
}
}
}
测试:
public class Test {
public static void main(String[] args) throws IOException {
ZipFiles.sourceToZip("C:\\Users\\DELL\\Desktop\\css",
"C:\\Users\\DELL\\Desktop\\");
}
}
结果: