集册 Java实例教程 使用ZipOutputStream从目录递归创建Zip文件

使用ZipOutputStream从目录递归创建Zip文件

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

717
使用ZipOutputStream从目录递归创建Zip文件
/** 
 来自 nowjava - 时  代  Java**/

 

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;


public class Main {


  public static void main(String args[]) {

    String sourceDir = "C:/examples";

    String zipFile = "C:/Folder/zipdemo.zip";


    try {
    /** 
     来自 时 代 J a v a 公 众 号 - N o w J a v  a . c o m**/

      FileOutputStream fout = new FileOutputStream(zipFile);

      ZipOutputStream zout = new ZipOutputStream(fout);

      File fileSource = new File(sourceDir);

      addDirectory(zout, fileSource);

      zout.close();

      System.out.println("Zip file has been created!");


    } catch (IOException ioe) {

      System.out.println("IOException :" + ioe);

    }

  }


  private static void addDirectory(ZipOutputStream zout, File fileSource) {

    File[] files = fileSource.listFiles();


    System.out.println("Adding directory " + fileSource.getName());


    for (int i = 0; i < files.length; i++) {

      if (files[i].isDirectory()) {

        addDirectory(zout, files[i]);

        continue;

      }

      try {

        System.out.println("Adding file " + files[i].getName());

        byte[] buffer = new byte[1024];


        // create object of FileInputStream

        FileInputStream fin = new FileInputStream(files[i]);


        zout.putNextEntry(
展开阅读全文