Golang 中的 archive/zip 包用于处理 ZIP 格式的压缩文件,提供了一系列用于创建、读取和解压缩 ZIP 格式文件的函数和类型,使用起来非常方便。
zip.File 类型
定义如下:
type File struct {FileHeaderzip *Readerzipr io.ReaderAtheaderOffset int64 // includes overall ZIP archive baseOffsetzip64 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 stringComment stringNonUTF8 boolCreatorVersion uint16ReaderVersion uint16Flags uint16Method uint16Modified time.TimeModifiedTime uint16ModifiedDate uint16CRC32 uint32CompressedSize uint32UncompressedSize uint32CompressedSize64 uint64UncompressedSize64 uint64Extra []byteExternalAttrs uint32 // Meaning depends on CreatorVersion
}
包含了文件在ZIP文件中的元数据信息,例如文件名、文件大小、修改时间等。
zip.Writer 类型
定义如下:
type Writer struct {cw *countWriterdir []*headerlast *fileWriterclosed boolcompressors map[uint16]Compressorcomment 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.ReaderAtFile []*FileComment stringdecompressors 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.OncefileList []fileListEntry
}
用于创建新的 ZIP 文件并将文件添加到其中。
zip.ReadCloser 类型
定义如下:
type ReadCloser struct {f *os.FileReader
}
用于读取文件的内容,并在读取完成后关闭文件。
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 类型的对象。