发一段JSP用ZIP实现在线压缩
看看能否抛砖引玉- //zip zhe folder
- void zip(String zipPath, String srcPath,javax.servlet.jsp.JspWriter out) throws Exception {
- FileOutputStream output = null;
- ZipOutputStream zipOutput = null;
- try{
- output = new FileOutputStream(zipPath);
- zipOutput = new ZipOutputStream(output);
- zipEntry(zipOutput,srcPath,srcPath,zipPath);
- }catch(Exception e){
- out.print("file zip error");
- }finally{
- if(zipOutput!=null)zipOutput.close();
- }
- out.print("zip ok"+zipPath);
- }
- //add the zip entry
- void zipEntry(ZipOutputStream zipOs, String initPath,String filePath,String zipPath) throws Exception {
- String entryName = filePath;
- File f = new File(filePath);
- if (f.isDirectory()){// ??
- String[] files = f.list();
- for(int i = 0; i < files.length; i++)
- zipEntry(zipOs, initPath, filePath + File.separator + files[i],zipPath);
- return;
- }
- String chPh = initPath.substring(initPath.lastIndexOf("/") + 1);// ?????
- int idx=initPath.lastIndexOf(chPh);
- if (idx != -1) {
- entryName = filePath.substring(idx);
- }
- ZipEntry entry;
- entry = new ZipEntry(entryName);
- File ff = new File(filePath);
- if(ff.getAbsolutePath().equals(zipPath))return;
- entry.setSize(ff.length());
- entry.setTime(ff.lastModified());
- //the CRC efficacy
- entry.setCrc(0);
- CRC32 crc = new CRC32();
- crc.reset();
- zipOs.putNextEntry(entry);
- int len = 0;
- byte[] buffer = new byte[2048];
- int bufferLen = 2048;
- FileInputStream input =null;
- try{
- input = new FileInputStream(filePath);
- while ((len = input.read(buffer, 0, bufferLen)) != -1) {
- zipOs.write(buffer, 0, len);
- crc.update(buffer, 0, len);
- }
- }catch(Exception e){
- }finally{
- if(input!=null)input.close();
- }
- entry.setCrc(crc.getValue());
- }
复制代码 |