Java创建zip压缩文件(不依赖第三方库)

话不多说,直接上代码:

import org.junit.Test;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class File2Zip {
	@Test
    public void test() {
		String rootPath = "C:\Users\Admin\AndroidStudioProjects\MyApplication\app\src\main\";
		File zipFile = new File(rootPath + "../测试压缩" + ".zip");
		try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFile))){
			zipFile(new File(rootPath), null, "", zipOutputStream);
		} catch (Exception e) {
			e.printStackTrace();
		}
    }

    public static void zipFile(File file, FilenameFilter filenameFilter, String basePath, ZipOutputStream zipOutputStream) throws IOException {
        if(basePath.length()>0 && !basePath.endsWith("\") && !basePath.endsWith("/")) {
			basePath += File.separator;
		}
        if (file.isDirectory()) {
			basePath += file.getName() + File.separator;
        	if (basePath.length()>0) {
				zipOutputStream.putNextEntry(new ZipEntry(basePath));
			}
			File[] arr = file.listFiles(filenameFilter);
        	if (arr!=null) {
				for (File f : arr) {
					zipFile(f, filenameFilter, basePath, zipOutputStream);
				}
			}
        }
        else {
        	try (FileInputStream fin = new FileInputStream(file)) {
				zipOutputStream.putNextEntry(new ZipEntry(basePath + file.getName()));
				byte[] data = new byte[4096];
				int len;
				while ((len = fin.read(data)) != -1) {
					zipOutputStream.write(data, 0, len);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
   
		}
    }
}

递归调用,参考了代码

如何指定是否包含顶级目录?

zipFile(new File(rootPath), null, "", zipOutputStream); // 不包含顶级目录

zipFile(new File(rootPath), null, "main", zipOutputStream); // 包含顶级目录

如何只压缩指定部分的目录?

比如只压缩 C:\Users\Admin\AndroidStudioProjects\MyApplication\app\src\main\文件夹下的 Java、reslayout 内容:

String rootPath = "C:\Users\TEST\AndroidStudioProjects\MyApplication\app\src\main\";
File zipFile = new File(rootPath + "代码和布局文件" + ".zip");
try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFile))){
	//zipOutputStream.putNextEntry(new ZipEntry("main\"));
	zipFile(new File(rootPath+"java"), null, "main", zipOutputStream);
	zipFile(new File(rootPath+"res\layout"), null, "main\res", zipOutputStream);
} catch (Exception e) {
	e.printStackTrace();
}

压缩单个文件

zipFile(new File(rootPath+"res\layout\test.xml"), null, "res\layout", zout);

轻松加愉快,惬意而迷人

经验分享 程序员 微信小程序 职场和发展