JAVA struts2框架下zip打包文件下载


用ant.jar中apache.tools中的ZipOutputStream来作为出入流(可能会有其他外层修饰),以byteArrayInputStream来作为输入流。

上代码:

action代码:

//代理下载
	public String agentDownload(){
		int dataSourceId = LoginInfo.getLoginUser().getDataSourceId();
		adminService = new AdminBLL(dataSourceId);
		String root = ServletActionContext.getServletContext().getRealPath("\\");
		String srcPath = root + "softs"+ File.separator+"Chart.js-master.zip";
		File file = new File(srcPath);
		input = adminService.downloadAgent(file);
		setAgentName("agent1.2");
		setMf("adm_monitor");
		return "agentDownload";
	}

业务代码:

public InputStream downloadAgent(File file){
		InputStream input = null;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		CheckedOutputStream cos = new CheckedOutputStream(out, new CRC32());
		ZipOutputStream zip = new ZipOutputStream(cos);
		ZipEntry entry = new ZipEntry(file.getName());
		InputStream is = null;
		try {
			zip.putNextEntry(entry);
			is = new BufferedInputStream(new FileInputStream(file));
			int buffer = 2048;
			byte[] data = new byte[buffer];
			int k;
			while( (k = is.read(data, 0, buffer)) != -1){
				zip.write(data, 0, k);
			}
			zip.flush();
			zip.closeEntry();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if(zip != null){
					zip.close();//必须要关闭,不然会出错
					input  = new ByteArrayInputStream(out.toByteArray());
				}
				if(is != null){
					is.close();
				}
			} catch (IOException e){
				e.printStackTrace();
			}
		}
		return input;
	}

注意点:

1、zip.flush()\zip.closeEntry()\zip.close();方法一定要调用,在调用close()方法后,才能开始转入输入流。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值