Attention: Here be dragons

This is the latest (unstable) version of this documentation, which may document features not available in or compatible with released stable versions of Godot.

ZIPReader

继承: RefCounted < Object

允许读取 ZIP 文件的内容。

描述

该类实现了能够从 ZIP 压缩包中提取各个文件内容的读取器。另见 ZIPPacker

# 读取 ZIP 压缩包中的单个文件。
func read_zip_file():
    var reader = ZIPReader.new()
    var err = reader.open("user://archive.zip")
    if err != OK:
        return PackedByteArray()
    var res = reader.read_file("hello.txt")
    reader.close()
    return res

# 解压 ZIP 压缩包中的所有文件,保持目录结构。
# 功能类似于大多数归档文件管理器中的“全部解压”功能。
func extract_all_from_zip():
    var reader = ZIPReader.new()
    reader.open("res://archive.zip")

    # 解压文件的目标目录(解压前必须存在)。
    # 不是所有的 ZIP 压缩包都会把所有文件都放在根文件夹中,
    # 解压后 `root_dir` 中会创建若干文件/文件夹。
    var root_dir = DirAccess.open("user://")

    var files = reader.get_files()
    for file_path in files:
        # 如果当前条目是目录。
        if file_path.ends_with("/"):
            root_dir.make_dir_recursive(file_path)
            continue

        # 写入文件内容,需要时自动创建文件夹。
        # 不是所有 ZIP 压缩包都遵循特定的顺序,这一步的作用是
        # 防止文件条目出现在文件夹条目之前。
        root_dir.make_dir_recursive(root_dir.get_current_dir().path_join(file_path).get_base_dir())
        var file = FileAccess.open(root_dir.get_current_dir().path_join(file_path), FileAccess.WRITE)
        var buffer = reader.read_file(file_path)
        file.store_buffer(buffer)

方法

Error

close()

bool

file_exists(path: String, case_sensitive: bool = true)

PackedStringArray

get_files()

Error

open(path: String)

PackedByteArray

read_file(path: String, case_sensitive: bool = true)


方法说明

Error close() 🔗

关闭该实例底层所使用的资源。


bool file_exists(path: String, case_sensitive: bool = true) 🔗

如果加载的 zip 存档中存在对应的文件,则返回 true

必须在 open() 之后调用。


PackedStringArray get_files() 🔗

返回加载的存档中所有文件的名称列表。

必须在 open() 之后调用。


Error open(path: String) 🔗

打开给定 path 的压缩文件,并读取其文件索引。


PackedByteArray read_file(path: String, case_sensitive: bool = true) 🔗

将加载的 zip 存档中文件的全部内容加载到内存中并返回它。

必须在 open() 之后调用。