日期:2014-05-20  浏览次数:20683 次

直接把字符串压缩成zip,输出到客户端下载
[code=HTML][/code]<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic"%>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
<%@ taglib uri="/WEB-INF/app.tld" prefix="app"%>
<%@ page import= "java.io.* " %> 
<%@ page import= "java.util.zip.* " %> 
<HTML> 
<BODY> 
<%  
response.setHeader( "Content-disposition", "attachment;filename="+ "book.zip ");  
response.setContentType("application/x-gzip;charset=UTF-8");


byte[] buf = new byte[1024];
ByteArrayInputStream bin = new ByteArrayInputStream("aasssssssssssssssssa".getBytes()); 
ByteArrayOutputStream baos = new ByteArrayOutputStream();//字符串输出流
int len = 0;
while ((len = bin.read(buf)) != -1) {
baos.write(buf, 0, len); 
}

ZipOutputStream zipOut = new ZipOutputStream(baos); //zip流包装
zipOut.putNextEntry(new ZipEntry("b.txt"));

OutputStream outa = response.getOutputStream();
outa.write(baos.toByteArray());//向客户端输出被包装成zip的流
response.flushBuffer(); 

zipOut.close();
baos.close(); 
bin.close();
outa.close();
%> 
</BODY> 
</HTML>

------解决方案--------------------
Java code

ByteArrayOutputStream baos = new ByteArrayOutputStream();//字符串输出流
int len = 0;
while ((len = bin.read(buf)) != -1) {
baos.write(buf, 0, len); 
}

ZipOutputStream zipOut = new ZipOutputStream(baos); //你这里的baos对象已经write完了,这里没了。
zipOut.putNextEntry(new ZipEntry("b.txt"));

------解决方案--------------------
try {

// Create the ZIP file
ZipOutputStream out = new ZipOutputStream(new ByteArrayOutputStream("aa").getBytes());

// Compress the files
FileInputStream in = new FileInputStream("aaaaaaaaaaa");

// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry("b.txt"));

// Transfer bytes from the file to the ZIP file
int len;
while ( (len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
// Complete the entry
out.closeEntry();

in.close();
// Complete the ZIP file
out.close();
}
catch (IOException e) {
e.printStackTrace();
}

这样。。。我没有测试。。你可以试试