java 实现压缩单个文件

先来实现一个简单的单文件压缩,主要是为了解一下压缩需要使用到的流。。

效果:

说明:压缩实现使用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 size
			zos = 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。

posted @ 2018-07-29 22:14  夯实点  阅读(316)  评论(0编辑  收藏  举报