I am trying to write a java ZIP util class as below:
package fdbank.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* 解压缩工具类
* @author ggfan@amarsoft
*
*/
public class ZIPUtil {
private static void zip(File[] files, String dest) throws IOException{
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(new File("dest")));
for(File file : files){
zip(file, zos);
}
zos.close();
}
private static void zip(File file, ZipOutputStream zos) throws IOException{
byte[] buf = new byte[2048];
@SuppressWarnings("unused")
int bytes = 0;
if(file.isDirectory()){
ZipEntry entry = new ZipEntry(file.getName());
zos.putNextEntry(entry);
for(File subFile : file.listFiles()){
zip(subFile, zos);
}
zos.closeEntry();
}
FileInputStream fis = new FileInputStream(file);
System.out.println(file.getName());
ZipEntry entry = new ZipEntry(file.getName());
zos.putNextEntry(entry);
while((bytes = fis.read(buf)) != -1){
zos.write(buf);
}
zos.closeEntry();
fis.close();
}
public static void compress(int archiveType, File[] files, String dest){
}
public static void main(String[] args){
try {
System.out.println("gan !!!!");
zip(new File[]{new File("F:\\ziptest\\1.bmp")},"c:\\ziptest.zip");
} catch (IOException e) {
e.printStackTrace();
}
}
}
I run it ,no error but the zip file not created at all!!!
what’s wrong with my code ?
You’re always writing to a file called “dest” and ignore the
Stringparameter calleddest(with the valuec:\ziptest.zip).Replace
"dest"withdeston the first line of your firstzip()method.Also: you must not ignore the return value of
fis.read(): Ifread()doesn’t fill the bufferbuf, then you must tell that to the correspondingwrite()call: