开发者

java ZipOutputStream problem

开发者 https://www.devze.com 2023-03-10 02:22 出处:网络
I am trying to write a java ZIP util class as below: package fdbank.util; import java.io.File; import java.io.FileInputStream;

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 s开发者_StackOverflow中文版tatic 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 String parameter called dest (with the value c:\ziptest.zip).

Replace "dest" with dest on the first line of your first zip() method.

Also: you must not ignore the return value of fis.read(): If read() doesn't fill the buffer buf, then you must tell that to the corresponding write() call:

while((bytes = fis.read(buf)) != -1){
    zos.write(buf, 0, bytes);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号