首页 > 编程 > JSP > 正文

JSP上面实现目录压缩

2024-09-05 00:20:31
字体:
来源:转载
供稿:网友

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


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表