HOWTO · Java

在 Java 中解壓縮檔案

本教程演示瞭如何在 Java 中提取 zip 檔案。

本頁內容

我們可以使用 Java 中內建的 Zip API 來提取 zip 檔案。本教程演示如何在 Java 中提取 zip 檔案。

在 Java 中解壓縮檔案

java.util.zip 用於解壓縮 Java 中的 zip 檔案。ZipInputStream 是用於讀取 zip 檔案並提取它們的主要類。

請按照以下步驟提取 Java 中的 zip 檔案。

  • 使用 ZipInputStreamFileInputStream 讀取 zip 檔案。
  • 使用 getNextEntry() 方法讀取條目。
  • 現在使用帶有位元組的 read() 方法讀取二進位制資料。
  • 使用 closeEntry() 方法關閉條目。
  • 最後,關閉 zip 檔案。

我們建立了一個函式來獲取輸入和目標路徑並提取檔案以實現這些步驟。壓縮檔案如下。

壓縮檔案

讓我們用 Java 實現上面的方法來提取如圖所示的 zip 檔案。

package delftstack;

import java.io.BufferedOutputStream;
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.ZipInputStream;

public class Java_Unzip {
  private static final int BUFFER_SIZE = 4096;
  public static void unzip(String ZipFilePath, String DestFilePath) throws IOException {
    File Destination_Directory = new File(DestFilePath);
    if (!Destination_Directory.exists()) {
      Destination_Directory.mkdir();
    }
    ZipInputStream Zip_Input_Stream = new ZipInputStream(new FileInputStream(ZipFilePath));
    ZipEntry Zip_Entry = Zip_Input_Stream.getNextEntry();

    while (Zip_Entry != null) {
      String File_Path = DestFilePath + File.separator + Zip_Entry.getName();
      if (!Zip_Entry.isDirectory()) {
        extractFile(Zip_Input_Stream, File_Path);
      } else {
        File directory = new File(File_Path);
        directory.mkdirs();
      }
      Zip_Input_Stream.closeEntry();
      Zip_Entry = Zip_Input_Stream.getNextEntry();
    }
    Zip_Input_Stream.close();
  }

  private static void extractFile(ZipInputStream Zip_Input_Stream, String File_Path)
      throws IOException {
    BufferedOutputStream Buffered_Output_Stream =
        new BufferedOutputStream(new FileOutputStream(File_Path));
    byte[] Bytes = new byte[BUFFER_SIZE];
    int Read_Byte = 0;
    while ((Read_Byte = Zip_Input_Stream.read(Bytes)) != -1) {
      Buffered_Output_Stream.write(Bytes, 0, Read_Byte);
    }
    Buffered_Output_Stream.close();
  }

  public static void main(String[] args) throws IOException {
    String ZipFilePath = "delftstack.zip";
    String DestFilePath = "C:\\Users\\Sheeraz\\eclipse-workspace\\Demos";
    unzip(ZipFilePath, DestFilePath);
    System.out.println("Zip File extracted Successfully");
  }
}

上述程式碼的輸出如下。

Zip File extracted Successfully

解壓檔案