我创建了一个压缩器,但存档已损坏,我不知道为什么

时间:2016-03-23 05:43:43

标签: java

我创建了一个压缩器,但存档已损坏,我不知道为什么。 我做错了什么?

当我运行此程序时,zip已成功构建,但存档已损坏且无法读取。

我不知道我的代码中缺少什么 - 我从博客中选择了此代码,但现在我不记得链接:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class AdvanceZip
{
    ArrayList<String> fileList;
    private static final String OUTPUT_ZIP_FILE = "/root/Desktop/JSP_Files/Jsp.zip";
    private static final String SOURCE_FOLDER = "/root/Desktop/JSP_Files/Jsp";

    AdvanceZip(){
    fileList = new ArrayList<String>();
    }

    public static void main( String[] args )
    {
        AdvanceZip AdvanceZip = new AdvanceZip();
        AdvanceZip.generateFileList(new File(SOURCE_FOLDER));
        AdvanceZip.zipIt(OUTPUT_ZIP_FILE);
    }

    /**
     * Zip it
     * @param zipFile output ZIP file location
     */
    public void zipIt(String zipFile){

     byte[] buffer = new byte[1024];

     try{

        FileOutputStream fos = new FileOutputStream(zipFile);
        ZipOutputStream zos = new ZipOutputStream(fos);

        System.out.println("Output to Zip : " + zipFile);

        for(String file : this.fileList){

            System.out.println("File Added : " + file);
            ZipEntry ze= new ZipEntry(file);
            zos.putNextEntry(ze);

            FileInputStream in = 
                       new FileInputStream(SOURCE_FOLDER + File.separator + file);

            int len;
            while ((len = in.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }

            in.close();
        }

        zos.closeEntry();


        System.out.println("Done");
    }catch(IOException ex){
       ex.printStackTrace();   
    }
   }

    /**
     * Traverse a directory and get all files,
     * and add the file into fileList  
     * @param node file or directory
     */
    public void generateFileList(File node){

        //add file only
    if(node.isFile()){
        fileList.add(generateZipEntry(node.getAbsoluteFile().toString()));
    }

    if(node.isDirectory()){
        String[] subNote = node.list();
        for(String filename : subNote){
            generateFileList(new File(node, filename));
        }
    }

    }

    /**
     * Format the file path for zip
     * @param file file path
     * @return Formatted file path
     */
    private String generateZipEntry(String file){
        return file.substring(SOURCE_FOLDER.length()+1, file.length());
    }
}

1 个答案:

答案 0 :(得分:1)

@gopal banger你没有关闭ZipOutputStream,这就是为什么你会遇到这样的错误..

zos.close();

之后

int len;
            while ((len = in.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }

            in.close();
        }

        zos.closeEntry();
//here