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());
}
新聞熱點
疑難解答