使用gzip技术对文件做压缩和解压缩

本文介绍了一个Gzip工具类的实现,包括数据压缩和解压缩的方法。此外,还详细展示了如何使用该工具类上传文件并进行压缩,以及解压缩并下载文件的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 gzip工具类:

package cn.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * Title: GzipUtils 
 * @date 2018年9月5日
 * @version V1.0 
 * Description:将文件或数据按照gzip方式压缩和解压缩
 */
@SuppressWarnings("all")
public class GzipUtils {

	// 压缩
	public static byte[] compress(byte[] data) throws IOException {
		if (data == null || data.length == 0) {
			return null;
		}
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		GZIPOutputStream gzip = new GZIPOutputStream(out);
		gzip.write(data);
		gzip.close();
		return out.toByteArray();// out.toString("ISO-8859-1");
	}

	public static byte[] compress(String str) throws IOException {
		if (str == null || str.length() == 0) {
			return null;
		}
		return compress(str.getBytes("utf-8"));
	}

	// 解压缩(数据)
	public static byte[] uncompress(byte[] data) throws IOException {
		if (data == null || data.length == 0) {
			return data;
		}
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ByteArrayInputStream in = new ByteArrayInputStream(data);
		GZIPInputStream gunzip = new GZIPInputStream(in);
		byte[] buffer = new byte[256];
		int n;
		while ((n = gunzip.read(buffer)) >= 0) {
			out.write(buffer, 0, n);
		}
		gunzip.close();
		in.close();
		return out.toByteArray();
	}

	public static String uncompress(String str) throws IOException {
		if (str == null || str.length() == 0) {
			return str;
		}
		byte[] data = uncompress(str.getBytes("utf-8")); // ISO-8859-1
		return new String(data);
	}
}

上传文件并压缩:

public R uploadFile(MultipartFile[] files, int type, String describe) {
    BufferedOutputStream stream = null;
	for (int i = 0; i < files.length; i++) {
		MultipartFile file = files[i];
		if (!file.isEmpty()) {
			// 获取文件名
			String filename = file.getOriginalFilename();
			if (filename.contains(".jsp")) {
				return R.error("您上传的文件格式不正确,请重新上传");
			}
			String folderName = "D://" + type + "/" + TimeUtils.toYM();
			File folderFile = new File(folderName);
			// 判断文件夹是否存在 不存在
			if (!folderFile.exists()) {
				folderFile.mkdirs();
			}
			// 新文件名
			String newFileName = IDUtils.genImageName()
					+ filename.substring(filename.indexOf("."), filename.length());
			String newFile = folderFile + "/" + newFileName;
			File departFile = new File(newFile);
			try {
				if (!departFile.exists()) {
					departFile.createNewFile();
				}
				// 压缩文件
				byte[] bytes = GzipUtils.compress(file.getBytes());
				stream = new BufferedOutputStream(new FileOutputStream(new File(newFile)));
				stream.write(bytes);
			} catch (Exception e) {
				return R.error("服务器繁忙,请稍后重试");
			} finally {
				try {
                       if(stream!=null){
                           stream.close();
                       }
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} else {
			return R.result(400, "上传文件不能为空");
		}
	}
		return R.ok("上传成功");
	}

解压缩并下载文件:

public R downloadFile(HttpServletResponse response, int fileId) {
	response.setHeader("content-type", "application/octet-stream");
	response.setContentType("application/octet-stream");
    String fileUrl="D://"+fileId;
	response.setHeader("Content-Disposition",
			"attachment;filename=" + fileUrl.substring(fileUrl.lastIndexOf("/") + 1, fileUrl.length()));
	File file = new File(fileUrl);
	if (!file.exists()) {
		return R.error("文件不存在");
	}
	FileInputStream fis = null;
	ByteArrayOutputStream bos = null;
	try {
		// 将file文件转成bytes 进行解压缩
		fis = new FileInputStream(file);
		bos = new ByteArrayOutputStream(fis.available());
		byte[] b = new byte[1024];
		int len = -1;
		while ((len = fis.read(b)) != -1) {
			bos.write(b, 0, len);
		}
		// 进行解压缩
		byte[] bytes = GzipUtils.uncompress(bos.toByteArray());
		response.getOutputStream().write(bytes);
		return R.ok("下载文件成功");
	} catch (Exception e) {
		e.printStackTrace();
		return R.error("文件下载失败");
	} finally {
	    try {
                if(fis!=null){
                    fis.close();
                }
	        if(bos!=null){
                    bos.close();
                }
	    } catch (IOException e) {
		    e.printStackTrace();
	    }
        }
    }else {
		    return R.error("文件不存在");
	      }	
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值