SoFunction
Updated on 2025-03-08

Java compressed file ZIP instance code


package ;
import ;
import ;
import ;
import ;
import ;
import ;
/**
* Compressed file
* @author Administrator
*
*/
public class SimpleZip {

public static final int BUFFER_SIZE = 1024;

public static void main(String[] args) throws IOException {
String src = "d:\\chat";
String des = "d:\\";
ZipOutputStream zos = null;
try{
zos = new ZipOutputStream(new FileOutputStream(des));
File srcFile = new File(src);
String base = ();
fileZip(srcFile,zos,base);
}catch (Exception e) {
// TODO: handle exception
();
}finally{
if(zos!=null){
();
}
}
("File compression is successful" + src);
}

private static void fileZip(File srcFile, ZipOutputStream zos, String base)
throws Exception{
// TODO Auto-generated method stub
if(!()){
("The file does not exist" + ());
}
if(()){
(new ZipEntry(base));
FileInputStream fis = new FileInputStream(srcFile);
byte[] buf = new byte[BUFFER_SIZE];
int n=0;
while((n=(buf, 0, ))!=-1){
(buf, 0, n);
}
();
}else{
if(()) {
base = base + ;
File[] subFiles = ();
for (File subFile : subFiles) {
fileZip(subFile, zos, base + ());
}
}
}
}
}