用Java压缩文件或目录下的所有文件

2008-02-23 09:34:39来源:互联网 阅读 ()

新老客户大回馈,云服务器低至5折

import Java.io.File;
import org.apache.tools.zip.ZipOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
/**
* @author tyrone
*
*/
public class DirectoryZip {
/**
*@param inputFileName, file or directory waiting for zipping ,outputFileName output file name
*
*/
public void zip(String inputFileName,String outputFileName) throws Exception {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outputFileName));
zip(out, new File(inputFileName), "");
System.out.println("zip done");
out.close();
}
private void zip(ZipOutputStream out, File f, String base) throws Exception {
if (f.isDirectory()) {
File[] fl = f.listFiles();
if (System.getProperty("os.name").startsWith("Windows")){
out.putNextEntry(new org.apache.tools.zip.ZipEntry(base "\\"));
base = base.length() == 0 ? "" : base "\\";
}
else{
out.putNextEntry(new org.apache.tools.zip.ZipEntry(base "/"));
base = base.length() == 0 ? "" : base "/";
}
for (int i = 0; i < fl.length; i ) {
zip(out, fl[i], base fl[i].getName());
}
}
else {
out.putNextEntry(new org.apache.tools.zip.ZipEntry(base));
FileInputStream in = new FileInputStream(f);
int b;
System.out.println(base);
while ( (b = in.read()) != -1) {
out.write(b);
}
in.close();
}
}
public static void main(String[] args){
DirectoryZip m_zip=new DirectoryZip();
try{
m_zip.zip(args[0],"release\\2005.zip");
}catch(Exception ex){
ex.printStackTrace();
}
}
}

上一篇: 使用Apache POI和Java获得Excel文件内容,无须MS-Office ActiveX OLE
下一篇: 使用TextMiniing和Apache POI获得Word文件内容,无须MS-Office ActiveX

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:使用ProcessBuilder调用外部命令,并返回大量结果

下一篇:中文字符乱码的原因及解决办法