解压缩压缩文件时出现问题

时间:2016-01-02 15:59:29

标签: java file zip

我使用以下代码创建文件夹的备份。以下代码创建一个zip文件,但我无法解压缩创建的文件。请帮我识别以下代码中的错误:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.bakeit.Configurations;

public class BakeSiteActionFacade {

    public void prepareDestination() throws IOException {

        if (!Paths.get(Configurations.BACKUP_PATH).toFile().exists()) {
                Files.createDirectories(Paths.get(Configurations.BACKUP_PATH));
        }
        File destinationFolder = null;
        zipDirectory(destinationFolder, Configurations.BACKUP_PATH
                + File.separator + "backup-"
                + new Date().toString().replaceAll(":", "").replaceAll(" ", "")
                + ".zip");
    }

    List<String> filesListInDir = new ArrayList<String>();

    private void zipDirectory(File dir, String zipDirName) {
        try {
            populateFilesList(dir);
            FileOutputStream fos = new FileOutputStream(zipDirName);
            ZipOutputStream zos = new ZipOutputStream(fos);
            for (String filePath : filesListInDir) {
                System.out.println("Zipping " + filePath);
                ZipEntry ze = new ZipEntry(filePath.substring(dir
                        .getAbsolutePath().length() + 1, filePath.length()));
                zos.putNextEntry(ze);
                FileInputStream fis = new FileInputStream(filePath);
                byte[] buffer = new byte[1024];
                int len;
                while ((len = fis.read(buffer)) > 0) {
                    zos.write(buffer, 0, len);
                }
                zos.closeEntry();
                fis.close();
            }
            zos.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void populateFilesList(File dir) throws IOException {
        File[] files = dir.listFiles();
        for (File file : files) {
            if (file.isFile())
                filesListInDir.add(file.getAbsolutePath());
            else
                populateFilesList(file);
        }
    }

}

PS:Configurations.BACKUP_PATH是一个String,其中包含备份文件夹的有效路径,该路径可能存在也可能不存在。

0 个答案:

没有答案