JAVA原生压缩算法类, 实现文件压缩,文件夹压缩,以及文件和文件夹的混合压缩(可在所有操作系统完美运行!)
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: jurui
* @Description: 压缩算法类, 实现文件压缩,文件夹压缩,以及文件和文件夹的混合压缩
* @Date: Created in 18:27 2019-09-06
*/
public class FileToZipUtil {
/**
* 压缩文件(可以是文件,也可以是文件夹)
*
* @param srcfile 待压缩文件
* @param targetFile 压缩后文件(可为空,会自动创建)
*/
public static void filesToZip(File srcfile, File targetFile) {
if (!srcfile.exists()){
return;
}
createFile(targetFile);
ZipOutputStream out = null;
try {
out = new ZipOutputStream(new FileOutputStream(targetFile));
if (srcfile.isFile()) {
zipFile(srcfile, out, "");
} else {
File[] list = srcfile.listFiles();
for (int i = 0; i < list.length; i++) {
compress(list[i], out, "");
}
}
System.out.println("压缩完毕");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null)
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 如果文件已经存在,则删除文件,如果文件父目录不存在,先创建文件父目录
* @param targetFile
*/
public static void createFile(File targetFile) {
if (targetFile.exists()) {
targetFile.delete();
}
if (!targetFile.getParentFile().exists()) {
targetFile.getParentFile().mkdirs();
}
}
/**
* 压缩文件夹里的文件
* 起初不知道是文件还是文件夹--- 统一调用该方法
*
* @param file
* @param out
* @param basedir
*/
private static void compress(File file, ZipOutputStream out, String basedir) {
/* 判断是目录还是文件 */
if (file.isDirectory()) {
zipDirectory(file, out, basedir);
} else {
zipFile(file, out, basedir);
}
}
/**
* 压缩单个文件
*
* @param srcfile
*/
public static void zipFile(File srcfile, ZipOutputStream out, String basedir) {
if (!srcfile.exists())
return;
byte[] buf = new byte[1024];
FileInputStream in = null;
try {
int len;
in = new FileInputStream(srcfile);
out.putNextEntry(new ZipEntry(basedir + srcfile.getName()));
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null)
out.closeEntry();
if (in != null)
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 压缩文件夹
*
* @param dir
* @param out
* @param basedir
*/
public static void zipDirectory(File dir, ZipOutputStream out, String basedir) {
if (!dir.exists())
return;
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
/* 递归 */
compress(files[i], out, basedir + dir.getName() + System.getProperty("file.separator"));
}
}
}