Golang 中的 archive/zip 包详解(二):常用类型

Golang 中的 archive/zip 包用于处理 ZIP 格式的压缩文件,提供了一系列用于创建、读取和解压缩 ZIP 格式文件的函数和类型,使用起来非常方便。

zip.File 类型

定义如下:

复制代码
type File struct {
	FileHeader
	zip          *Reader
	zipr         io.ReaderAt
	headerOffset int64 // includes overall ZIP archive baseOffset
	zip64        bool  // zip64 extended information extra field presence
}

表示一个 ZIP 文件中的单个文件的信息,文件的元数据信息,例如文件名、文件大小、修改时间等包含在 FileHeader 中,有两个重要的方法:

  • func (f *File) DataOffset() (offset int64, err error),返回文件的可能存在的压缩数据相对于 zip 文件起始的偏移量。
  • func (f *File) Open() (rc io.ReadCloser, err error),返回一个 io.ReadCloser 类型的对象,提供读取文件内容的方法。

zip.FileHeader 类型

定义如下:

复制代码
type FileHeader struct {
	Name string
	Comment string
	NonUTF8 bool
	CreatorVersion uint16
	ReaderVersion  uint16
	Flags          uint16
	Method uint16
	Modified time.Time
	ModifiedTime uint16
	ModifiedDate uint16
	CRC32 uint32
	CompressedSize uint32
	UncompressedSize uint32
	CompressedSize64 uint64
	UncompressedSize64 uint64
	Extra         []byte
	ExternalAttrs uint32 // Meaning depends on CreatorVersion
}

包含了文件在ZIP文件中的元数据信息,例如文件名、文件大小、修改时间等。

zip.Writer 类型

定义如下:

复制代码
type Writer struct {
	cw          *countWriter
	dir         []*header
	last        *fileWriter
	closed      bool
	compressors map[uint16]Compressor
	comment     string

	// testHookCloseSizeOffset if non-nil is called with the size
	// of offset of the central directory at Close.
	testHookCloseSizeOffset func(size, offset uint64)
}

实现了一个 zip 文件写入器。

zip.Reader 类型

定义如下:

复制代码
type Reader struct {
	r             io.ReaderAt
	File          []*File
	Comment       string
	decompressors map[uint16]Decompressor

	// Some JAR files are zip files with a prefix that is a bash script.
	// The baseOffset field is the start of the zip file proper.
	baseOffset int64

	// fileList is a list of files sorted by ename,
	// for use by the Open method.
	fileListOnce sync.Once
	fileList     []fileListEntry
}

用于创建新的 ZIP 文件并将文件添加到其中。

zip.ReadCloser 类型

定义如下:

复制代码
type ReadCloser struct {
	f *os.File
	Reader
}

用于读取文件的内容,并在读取完成后关闭文件。

zip.Compressor 类型

定义如下:

复制代码
type Compressor func(w io.Writer) (io.WriteCloser, error)

返回一个用于压缩用途的 io.WriteCloser 类型的对象。

zip.Decompressor 类型

定义如下:

复制代码
type Decompressor func(r io.Reader) io.ReadCloser

返回一个用于解压缩用途的 io.ReadCloser 类型的对象。

相关推荐
IT_10241 小时前
Spring Boot项目开发实战销售管理系统——系统设计!
大数据·spring boot·后端
ai小鬼头2 小时前
AIStarter最新版怎么卸载AI项目?一键删除操作指南(附路径设置技巧)
前端·后端·github
Touper.2 小时前
SpringBoot -- 自动配置原理
java·spring boot·后端
黄雪超2 小时前
JVM——函数式语法糖:如何使用Function、Stream来编写函数式程序?
java·开发语言·jvm
ThetaarSofVenice2 小时前
对象的finalization机制Test
java·开发语言·jvm
思则变3 小时前
[Pytest] [Part 2]增加 log功能
开发语言·python·pytest
一只叫煤球的猫3 小时前
普通程序员,从开发到管理岗,为什么我越升职越痛苦?
前端·后端·全栈
一只鹿鹿鹿3 小时前
信息化项目验收,软件工程评审和检查表单
大数据·人工智能·后端·智慧城市·软件工程
lijingguang3 小时前
在C#中根据URL下载文件并保存到本地,可以使用以下方法(推荐使用现代异步方式)
开发语言·c#
专注VB编程开发20年3 小时前
开机自动后台运行,在Windows服务中托管ASP.NET Core
windows·后端·asp.net