Java压缩文件ZIP实例代码

时间:2022-03-25 04:08:27 

提示:java.util.zipoutputstream

        java API压缩为zip文件

代码:


package com.gaoqi.test;
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 Administrator
*
*/
public class SimpleZip {

public static final int BUFFER_SIZE = 1024;

public static void main(String[] args) throws IOException {
String src = "d:\\chat";
String des = "d:\\chat01.zip";
ZipOutputStream zos = null;
try{
zos = new ZipOutputStream(new FileOutputStream(des));
File srcFile = new File(src);
String base = srcFile.getName();
fileZip(srcFile,zos,base);
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
if(zos!=null){
zos.close();
}
}
System.out.println("文件压缩成功啦" + src);
}

private static void fileZip(File srcFile, ZipOutputStream zos, String base)
throws Exception{
// TODO Auto-generated method stub
if(!srcFile.exists()){
System.out.println("文件不存在" + srcFile.getPath());
}
if(srcFile.isFile()){
zos.putNextEntry(new ZipEntry(base));
FileInputStream fis = new FileInputStream(srcFile);
byte[] buf = new byte[BUFFER_SIZE];
int n=0;
while((n=fis.read(buf, 0, buf.length))!=-1){
zos.write(buf, 0, n);
}
fis.close();
}else{
if(srcFile.isDirectory()) {
base = base + File.separator;
File[] subFiles = srcFile.listFiles();
for (File subFile : subFiles) {
fileZip(subFile, zos, base + subFile.getName());
}
}
}
}
}

标签:压缩文件,ZIP
0
投稿

猜你喜欢

  • IDEA无法使用Git Pull的问题

    2023-05-04 10:55:39
  • Java利用HttpClient模拟POST表单操作应用及注意事项

    2023-11-29 23:48:01
  • Android统一依赖管理的三种方式总结

    2021-06-13 02:44:48
  • Spring Boot 项目发布到 Tomcat 服务器的操作步骤

    2023-10-28 09:39:05
  • android自定义view用path画长方形

    2022-07-20 21:03:00
  • android studio节省C盘空间的配置方法

    2023-07-04 16:43:20
  • Java多线程ThreadPoolExecutor详解

    2023-11-23 18:39:32
  • Windows下搭建Flutter开发环境

    2023-11-06 01:32:52
  • Springboot创建子父工程过程图解

    2022-09-20 06:06:26
  • Android开发笔记之:返回键的复写onBackPressed()介绍

    2022-04-29 17:54:40
  • Java 17 更快的 LTS 节奏

    2023-07-08 11:36:19
  • idea的使用之关于tomcat热部署的教程

    2022-12-02 20:16:46
  • 代码详解Java猴子选王问题(约瑟夫环)

    2023-09-16 07:33:43
  • Android项目实战手把手教你画圆形水波纹loadingview

    2023-03-15 10:13:47
  • c# 反射+自定义特性保存数据至本地

    2023-03-14 03:07:40
  • C#正则实现Ubb解析类的代码

    2021-10-23 22:19:38
  • 3种C# 加载Word的方法

    2021-06-05 21:06:41
  • Java实现布隆过滤器的方法步骤

    2023-02-15 20:31:47
  • Android Studio配置Kotlin开发环境详细步骤

    2022-10-09 21:29:35
  • RabbitMQ消息有效期与死信的处理过程

    2023-11-10 20:29:42
  • asp之家 软件编程 m.aspxhome.com