JavaWeb实现tar包边压缩边下载

简介:

常见的文件打包是在服务器进行文件压缩打成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();
		}
	}
}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
JavaWeb实现文件下载需要以下步骤: 1. 获取要下载文件路径和文件名。 2. 创建一个输入流将文件读进来。 3. 设置响应头,告诉浏览器返回的是一个文件,以及文件名和大小。 4. 创建一个输出流将文件写到浏览器中。 下面是一个简单的示例代码: ``` protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取要下载文件路径和文件名 String filePath = "C:/files/"; String fileName = "file.txt"; File file = new File(filePath + fileName); if (!file.exists()) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // 设置响应头,告诉浏览器返回的是一个文件,以及文件名和大小 response.setContentType("application/octet-stream"); response.setContentLength((int) file.length()); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); // 创建一个输入流将文件读进来 FileInputStream fis = new FileInputStream(file); // 创建一个输出流将文件写到浏览器中 OutputStream os = response.getOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) != -1) { os.write(buffer, 0, len); } fis.close(); os.close(); } ``` 在这个示例中,我们假设要下载文件名为file.txt,存储在C:/files/下面。首先判断文件是否存在,如果不存在,返回404错误。然后设置响应头,告诉浏览器返回的是一个文件,以及文件名和大小。接着创建一个输入流将文件读进来,再创建一个输出流将文件写到浏览器中。最后关闭输入流和输出流。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值