JSP上面實現目錄壓縮

來源:互聯網
上載者:User
js|壓縮

zip方法 zipPath參數為儲存zip的檔案路徑  srcPath參數為需要壓縮的目錄   在linux window上面測試無問題!主要是編碼問題比較麻煩~要是有其他異常 請留言 或者 有什麼更好的方法 歡迎給更多的意見

//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());




相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.