JavaWeb实现tar包边压缩边下载

本文介绍了一种服务器文件处理方法,通过使用commons-compress库实现在服务器上对文件实时压缩并直接下载,避免了临时文件的生成,节省了服务器资源。

简介:

常见的文件打包是在服务器进行文件压缩打成tar包,然后再进行下载,最后还要删除掉临时的tar包,对于服务器来说会占用一定的资源。
以下代码是本人工作时项目所用到的,实现服务器文件边压缩打包边下载。
以下时具体的maven配置包
        <dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-csv</artifactId>
			<version>1.5</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-compress</artifactId>
			<version>1.9</version>
		</dependency>

import org.apache.commons.io.IOUtils;
import org.apache.comons.compress.archivers.tar.TarArchiveEntry;
imort org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;


@RequestMapping(value = "tar/export/{}")
public void tarExport(HttpServletRequest request, HttpServletResponse response)throws IOException{
	OutputStream os = response.getOutputStream();
	//设置打包的名称
	String tarName = "package.tar";
	//所要打包的文件夹路径
	String packagePath = "       ";
	response.setCharacterEncoding("UTF-8");
	response.setContentType("octets/stream");
	String agent = request.getHeader("USER-AGENT");
	try{
		if(agent.contains("MSIE") || agent.contains("Trident")){
			tarName = URLEncoder.encoder(tarName, "UTF-8");
		}else{
			tarName = new String(tarName.getBytes("UTF-8"), "ISO-8859-1");
		}
	}catch(UnsupportedEncodingException e){
		//采用log4j进行日志输出
		logger.error(e.getMessage, e);
	}
	response.setHeader("Content-Disposition", "attachment;fileName=\"" + tarName + "\"");
	TarArchiveOutputStream taos = null;
	InputStream is = null;
	try{
		taos = new TarArchiveOutputStream(os);
		String[] fileNameArray = new File(packagePath).list();
		for(String fileName : fileNameArray){
			File file = new File(packagePath + File.separator + fileName);
			TarArchiveEntry entry = new TarArchiveEntry(fileName);
			entry.setSize(file.length());
			taos.putArchiveEntry(entry);
			is = new FileInputStream(file);
			//这里采用IOUtils工具类,将输入流写到输出流中
			IOUtils.copy(is, taos);
			//inputStream创建于for循环内部,所以需要再循环结束时,将其关闭
			is.close();
			taos.closeArchiveEntry();
		}
	}catch(Exception e){
		logger.error(e.getMessage, e);
	}finally{
	//推荐使用try-with-resource 方式进行连接的关闭
		if(taos != null){
			taos.flush();
			taos.close();
		}
		if(os != null){
			os.flush();
			os.close();
		}
	}
}

本文章系博主原创,尊重博主辛劳成果,转载请注明出处,谢谢。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值