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

使用ZipOutputStream从多个文件创建Zip文件

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

967
使用ZipOutputStream从多个文件创建Zip文件
/*N  o w  J a v a . c o m*/


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[]) {

    try {

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

      String[] sourceFiles = { "C:/file1.doc", "C:/file2.doc" };// from n o w    j a v a  . c o m

      byte[] buffer = new byte[1024];

      FileOutputStream fout = new FileOutputStream(zipFile);

      ZipOutputStream zout = new ZipOutputStream(fout);

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

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

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

        zout.putNextEntry(new ZipEntry(sourceFiles[i]));

        int length;


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

          zout.write(buffer, 0, length);

        }

        zout.clo
展开阅读全文