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

解压文件