集册 Java实例教程 创建ZIP文件

创建ZIP文件

欢马劈雪     最近更新时间:2020-01-02 10:19:05

523
创建ZIP文件
/*N o w J a v a . c o m - 时  代  Java*/


//package com.nowjava;

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;


import java.util.zip.ZipEntry;

import java.util.zip.ZipException;


import java.util.zip.ZipOutputStream;


public class Main {

    private static final int BUFFER = 2048;


    public static void createZipFile(String path, String zipName) {

        File dir = new File(path);
        /**来自 
         N o w J a v a . c o m - 时  代  Java**/


        String[] list = dir.list();

        String _path;


        if (!dir.canRead() || !dir.canWrite())

            return;


        int len = list.length;


        if (path.charAt(path.length() - 1) != '/')

            _path = path + "/";

        else

            _path = path;


        try {

            ZipOutputStream zip_out = new ZipOutputStream(

                    new BufferedOutputStream(new FileOutputStream(zipName),

                            BUFFER));


            for (int i = 0; i < len; i++)

                zip_folder(new File(_path + list[i]), zip_out);


            zip_out.close();

        } catch (FileNotFoundException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }

    }


    public static void zip_folder(File file, ZipOutputStream zout)

            throws ZipException, IOException {

        byte[] data = new byte[BUFFER];

        int read;


        if (file.isFile()) {

            ZipEntry entry = new ZipEntry(file.getName());

            zout.putNextEntry(entry);

            BufferedInputStream instream = new BufferedInputStream(

                    new FileInputStream(file));


            while ((read = in
展开阅读全文