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

使用ZipOutputStream从目录创建Zip文件

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

1000
使用ZipOutputStream从目录创建Zip文件


import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;//时 代 J     a    v  a - nowjava.com 提供

import java.io.IOException;

import java.util.zip.ZipEntry;

import java.util.zip.ZipOutputStream;


public class Main {


  public static void main(String args[]) {

    try {

      String zipFile = "C:/Folder/zipdemo.zip";/*来自 时   代    Java - nowjava.com*/

      String sourceDirectory = "C:/examples";


      // create byte buffer

      byte[] buffer = new byte[1024];

      FileOutputStream fout = new FileOutputStream(zipFile);


      ZipOutputStream zout = new ZipOutputStream(fout);


      File dir = new File(sourceDirectory);


      if (!dir.isDirectory()) {

        System.out.println(sourceDirectory + " is not a directory");

      } else {

        File[] files = dir.listFiles();


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

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


          // create object of FileInputStream for source file

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


          zout.putNextEntry(new ZipEntry(files[i].getName()));


          int length;


          while ((length = fin.read(buffer)) > 0) {

            zout.write(buffer, 0, length);

          }


          zout.closeEntry();


          
展开阅读全文