Java Zip文件文件夹示例

时间:2020-02-23 14:37:01  来源:igfitidea点击:

今天,我们将研究java zip文件示例。
我们还将使用Java程序压缩文件夹并创建zip文件。

Java ZIP

java.util.zip.ZipOutputStream可用于将文件压缩为ZIP格式。
由于一个zip文件可以包含多个条目,因此ZipOutputStream使用java.util.zip.ZipEntry表示一个zip文件条目。

Java ZIP文件

为单个文件创建一个zip存档非常容易,我们需要从目标文件的FileOutputStream对象创建一个ZipOutputStream对象。
然后,我们将新的ZipEntry添加到ZipOutputStream并使用FileInputStream读取源文件到ZipOutputStream对象。
完成编写后,我们需要关闭ZipEntry并释放所有资源。

Java Zip文件夹

压缩目录有点棘手,首先我们需要获取文件列表作为绝对路径。
然后分别处理每个。
我们需要为每个文件添加一个ZipEntry,并使用FileInputStream将源文件的内容读取到与该文件相对应的ZipEntry。

Java Zip示例

这是Java程序,显示了如何在Java中压缩单个文件或者压缩文件夹。

package com.theitroad.files;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFiles {
  
  List<String> filesListInDir = new ArrayList<String>();

  public static void main(String[] args) {
      File file = new File("/Users/hyman/sitemap.xml");
      String zipFileName = "/Users/hyman/sitemap.zip";
      
      File dir = new File("/Users/hyman/tmp");
      String zipDirName = "/Users/hyman/tmp.zip";
      
      zipSingleFile(file, zipFileName);
      
      ZipFiles zipFiles = new ZipFiles();
      zipFiles.zipDirectory(dir, zipDirName);
  }

  /**
   * This method zips the directory
   * @param dir
   * @param zipDirName
   */
  private void zipDirectory(File dir, String zipDirName) {
      try {
          populateFilesList(dir);
          //now zip files one by one
          //create ZipOutputStream to write to the zip file
          FileOutputStream fos = new FileOutputStream(zipDirName);
          ZipOutputStream zos = new ZipOutputStream(fos);
          for(String filePath : filesListInDir){
              System.out.println("Zipping "+filePath);
              //for ZipEntry we need to keep only relative file path, so we used substring on absolute path
              ZipEntry ze = new ZipEntry(filePath.substring(dir.getAbsolutePath().length()+1, filePath.length()));
              zos.putNextEntry(ze);
              //read the file and write to ZipOutputStream
              FileInputStream fis = new FileInputStream(filePath);
              byte[] buffer = new byte[1024];
              int len;
              while ((len = fis.read(buffer)) > 0) {
                  zos.write(buffer, 0, len);
              }
              zos.closeEntry();
              fis.close();
          }
          zos.close();
          fos.close();
      } catch (IOException e) {
          e.printStackTrace();
      }
  }
  
  /**
   * This method populates all the files in a directory to a List
   * @param dir
   * @throws IOException
   */
  private void populateFilesList(File dir) throws IOException {
      File[] files = dir.listFiles();
      for(File file : files){
          if(file.isFile()) filesListInDir.add(file.getAbsolutePath());
          else populateFilesList(file);
      }
  }

  /**
   * This method compresses the single file to zip format
   * @param file
   * @param zipFileName
   */
  private static void zipSingleFile(File file, String zipFileName) {
      try {
          //create ZipOutputStream to write to the zip file
          FileOutputStream fos = new FileOutputStream(zipFileName);
          ZipOutputStream zos = new ZipOutputStream(fos);
          //add a new Zip Entry to the ZipOutputStream
          ZipEntry ze = new ZipEntry(file.getName());
          zos.putNextEntry(ze);
          //read the file and write to ZipOutputStream
          FileInputStream fis = new FileInputStream(file);
          byte[] buffer = new byte[1024];
          int len;
          while ((len = fis.read(buffer)) > 0) {
              zos.write(buffer, 0, len);
          }
          
          //Close the zip entry to write to zip file
          zos.closeEntry();
          //Close resources
          zos.close();
          fis.close();
          fos.close();
          System.out.println(file.getCanonicalPath()+" is zipped to "+zipFileName);
          
      } catch (IOException e) {
          e.printStackTrace();
      }

  }

}

上面的Java zip示例程序的输出为:

/Users/hyman/sitemap.xml is zipped to /Users/hyman/sitemap.zip
Zipping /Users/hyman/tmp/.DS_Store
Zipping /Users/hyman/tmp/data/data.dat
Zipping /Users/hyman/tmp/data/data.xml
Zipping /Users/hyman/tmp/data/xmls/project.xml
Zipping /Users/hyman/tmp/data/xmls/web.xml
Zipping /Users/hyman/tmp/data.Xml
Zipping /Users/hyman/tmp/DB.xml
Zipping /Users/hyman/tmp/item.XML
Zipping /Users/hyman/tmp/item.xsd
Zipping /Users/hyman/tmp/ms/data.txt
Zipping /Users/hyman/tmp/ms/project.doc

请注意,在将文件记录为zip时,我正在打印绝对路径。
但是,在添加zip条目时,我使用的是目录的相对路径,因此当我们解压缩它时,它将创建相同的目录结构。