用Java压缩文件或目录下的所有文件
2008-01-05 08:31:39 来源:WEB开发网
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();
}
}
}
更多精彩
赞助商链接