用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()方法后,才能开始转入输入流。