Java的文件压缩-Zip格式

/**
  * 文件压缩
  */
public class ZipFile_Compress {
    public static void main(String[] args) throws IOException {
        File file = new File("E:\\aaa\\web01");

        String savePath = "E:\\aaa" + File.separator + file.getName() + ".zip";
        File saveFile = new File(savePath);
        if (!saveFile.getParentFile().exists()) {
            saveFile.getParentFile().mkdirs();
        }

        ZipOutputStream outputStream = new ZipOutputStream(new FileOutputStream(savePath, true));

        toMakeZipFilePre(file, saveFile.getParentFile().getPath(), outputStream);

        outputStream.close();
    }

    /**
     * 文件压缩前的准备处理
     * @param file
     * @param savePath
     * @param outputStream
     * @throws IOException
     */
    public static void toMakeZipFilePre(File file, String savePath, ZipOutputStream outputStream) throws IOException {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files != null) {
                for (File f : files) {
                    toMakeZipFilePre(f, savePath, outputStream);
                }
            }
        } else {
            /**
             * 截取后面要用的文件条目
             */
            String realSavePath = file.getAbsolutePath().substring(savePath.length() + 1).replaceAll("\\\\", "/");
            toMakeZipFile(file, realSavePath, outputStream);
            System.out.println(realSavePath);
        }
    }

    public static void toMakeZipFile(File file, String savePath, ZipOutputStream outputStream) throws IOException {
        /**
         * 将相对路径封装成条目
         */
        ZipEntry zipEntry = new ZipEntry(savePath);
        /**
         * 在输出流中编写一条新的条目
         */
        outputStream.putNextEntry(zipEntry);

        InputStream inputStream = new BufferedInputStream(new FileInputStream(file));

        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
        }
        outputStream.flush();
        inputStream.close();
    }

}

评论

暂无评论