先来实现一个简单的单文件压缩,主要是为了解一下压缩需要使用到的流。。
效果:
说明:压缩实现使用ZipOutputStream
代码:
package com.gx.compress;import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
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;/**
* @ClassName: CompressUtil
* @Description: 压缩单个文件
* @author zhoujie
* @date 2018年7月29日 下午9:56:29
* @version V1.0*/
public class CompressUtil {static String path = "F:\\图片\\"; //文件夹路径public static void main(String[] args) {String filePath = path + "铜钱.jpg"; //图片名称String outPath = path + "new.zip"; //压缩文件名称地址zipUtil(filePath, outPath); //压缩}public static void zipUtil(String filePath, String outPath){//输入File file = null;FileInputStream fis = null;BufferedInputStream bin = null;DataInputStream dis = null;//输出File outfile = null;FileOutputStream fos = null;BufferedOutputStream bos = null;ZipOutputStream zos = null;ZipEntry ze = null;try {//输入-获取数据file = new File(filePath);fis = new FileInputStream(file);bin = new BufferedInputStream(fis);dis = new DataInputStream(bin); //增强//输出-写出数据outfile = new File(outPath);fos = new FileOutputStream(outfile); bos = new BufferedOutputStream(fos, 1024); //the buffer sizezos = new ZipOutputStream(bos); //压缩输出流ze = new ZipEntry(file.getName()); //实体ZipEntry保存zos.putNextEntry(ze);int len = 0;//临时文件byte[] bts = new byte[1024]; //读取缓冲while((len=dis.read(bts)) != -1){ //每次读取1024个字节System.out.println(len);zos.write(bts, 0, len); //每次写len长度数据,最后前一次都是1024,最后一次len长度}System.out.println("压缩成功");} catch (Exception e) {e.printStackTrace();} finally{try { //先实例化后关闭zos.closeEntry();zos.close();bos.close();fos.close();dis.close();bin.close();fis.close();} catch (IOException e) {e.printStackTrace();}}}}
以上仅为单个文件压缩,了解压缩流程。
下面这个是支持 单文件 或 文件夹 压缩:
java 实现压缩文件(单文件 或 文件夹)
ok。