zip 包

import "archive/zip"

概览

Package zip provides support for reading and writing ZIP archives.
zip 包提供了对 ZIP 归档文件写入和读取的支持。

ZIP介绍:https://www.pkware.com/appnote

This package does not support disk spanning.
该包不支持跨磁盘操作。

A note about ZIP64:
有关ZIP64的说明:

To be backwards compatible the FileHeader has both 32 and 64 bit Size fields. The 64 bit fields will always contain the correct value and for normal archives both fields will be the same. For files requiring the ZIP64 format the 32 bit fields will be 0xffffffff and the 64 bit fields must be used instead.
为了向后兼容,FileHeader包含32位和64位标识字段。对于普通归档,64位字段始终包含正确的值,这种情况下这两个字段是相同的。对于需要ZIP64格式的文件,32位字段的值是0xffffffff,该格式必须使用64位字段。

索引

Constants

Compression methods.
压缩方式

const (
        Store   uint16 = 0
        Deflate uint16 = 8
)

Variables

var (
        ErrFormat    = errors.New("zip: not a valid zip file")
        ErrAlgorithm = errors.New("zip: unsupported compression algorithm")
        ErrChecksum  = errors.New("zip: checksum error")
)

func RegisterCompressor

func RegisterCompressor(method uint16, comp Compressor)

RegisterCompressor registers custom compressors for a specified method ID. The common methods Store and Deflate are built in.
RegisterCompressor为指定的方法ID注册自定义压缩器。内置压缩器有Store和Deflate。

func RegisterDecompressor

func RegisterDecompressor(method uint16, dcomp Decompressor)

RegisterDecompressor allows custom decompressors for a specified method ID. The common methods Store and Deflate are built in.
RegisterDecompressor为指定的方法ID注册自定义解压缩器。内置解压缩器有Store和Deflate。

type Compressor

A Compressor returns a new compressing writer, writing to w. The WriteCloser's Close method must be used to flush pending data to w. The Compressor itself must be safe to invoke from multiple goroutines simultaneously, but each returned writer will be used only by one goroutine at a time.
Compressor能够返回一个向w进行写入操作的压缩写入器。必须使用WriteCloser的Close方法将未处理的数据flush到w。Compressor本身必须是安全的,可以同时调用多个goroutine,但每个返回的writer只能被一个goroutine使用。

type Compressor func(w io.Writer) (io.WriteCloser, error)

type Decompressor

A Decompressor returns a new decompressing reader, reading from r. The ReadCloser's Close method must be used to release associated resources. The Decompressor itself must be safe to invoke from multiple goroutines simultaneously, but each returned reader will be used only by one goroutine at a time.
Decompressor能够返回一个向r进行读取操作的解压缩读取器。必须使用ReadCloser的Close方法来释放相关资源。Decompressor本身必须安全地同时调用多个goroutine,但每个返回的reader只能被一个goroutine使用。

type Decompressor func(r io.Reader) io.ReadCloser

type File

type File struct {
        FileHeader
        // contains filtered or unexported fields
}

func (f *File) DataOffset() (offset int64, err error)

func (f *File) DataOffset() (offset int64, err error)

DataOffset returns the offset of the file's possibly-compressed data, relative to the beginning of the zip file.
DataOffset返回文件可能压缩的数据,这个数据是相对于zip文件开始的偏移量。

Most callers should instead use Open, which transparently decompresses data and verifies checksums.
大多数调用者应该使用Open函数替代,Open会计算解压缩数据并验证校验和。

func (*File) Open

func (f *File) Open() (io.ReadCloser, error)

Open returns a ReadCloser that provides access to the File's contents. Multiple files may be read concurrently.
Open返回一个ReadCloser,它提供对文件内容的访问。可以同时读取多个文件。

type FileHeader

FileHeader describes a file within a zip file. See the zip spec for details.
FileHeader描述了zip中的一个文件。详细信息,参阅zip规范。

type FileHeader struct {
        // Name is the name of the file.
        // It must be a relative path: it must not start with a drive
        // letter (e.g. C:) or leading slash, and only forward slashes
        // are allowed.
        Name string

        CreatorVersion     uint16
        ReaderVersion      uint16
        Flags              uint16
        Method             uint16
        ModifiedTime       uint16 // MS-DOS time
        ModifiedDate       uint16 // MS-DOS date
        CRC32              uint32
        CompressedSize     uint32 // Deprecated: Use CompressedSize64 instead.
        UncompressedSize   uint32 // Deprecated: Use UncompressedSize64 instead.
        CompressedSize64   uint64
        UncompressedSize64 uint64
        Extra              []byte
        ExternalAttrs      uint32 // Meaning depends on CreatorVersion
        Comment            string
}

func FileInfoHeader

func FileInfoHeader(fi os.FileInfo) (*FileHeader, error)

FileInfoHeader creates a partially-populated FileHeader from an os.FileInfo. Because os.FileInfo's Name method returns only the base name of the file it describes, it may be necessary to modify the Name field of the returned header to provide the full path name of the file.
FileInfoHeader从os.FileInfo中创建一个字段部分填充的FileHeader。由于os.FileInfo的Name方法只返回它描述的文件的基本名称,所以可能需要修改返回的头的Name字段以提供文件的完整路径名。

func (*FileHeader) FileInfo

func (h *FileHeader) FileInfo() os.FileInfo

FileInfo returns an os.FileInfo for the FileHeader.
FileInfo返回h的os.FileInfo数据。

func (*FileHeader) ModTime

func (h *FileHeader) ModTime() time.Time

ModTime returns the modification time in UTC. The resolution is 2s.
ModTime返回UTC格式的文件的修改时间。精确度间隔是2s。

func (*FileHeader) Mode

func (h *FileHeader) Mode() (mode os.FileMode)

Mode returns the permission and mode bits for the FileHeader.
Mode返回位于FileHeader中的权限和类型信息。

func (*FileHeader) SetModTime

func (h *FileHeader) SetModTime(t time.Time)

SetModTime sets the ModifiedTime and ModifiedDate fields to the given time in UTC. The resolution is 2s.
SetModTime将ModifiedTime和ModifiedDate字段设置为UTC格式的时间。精确度间隔是2s。

func (*FileHeader) SetMode

func (h *FileHeader) SetMode(mode os.FileMode)

SetMode changes the permission and mode bits for the FileHeader.
SetMode更改FileHeader的权限和类型信息。

type ReadCloser

type ReadCloser struct {
        Reader
        // contains filtered or unexported fields
}

func OpenReader

func OpenReader(name string) (*ReadCloser, error)

OpenReader will open the Zip file specified by name and return a ReadCloser.
OpenReader打开指定名称的Zip文件并返回一个ReadCloser。

func (*ReadCloser) Close()

func (rc *ReadCloser) Close() error

Close closes the Zip file, rendering it unusable for I/O.
Close关闭Zip文件操作,使其不能用于I/O。

type Reader

type Reader struct {
        File    []*File
        Comment string
        // contains filtered or unexported fields
}

示例

// Open a zip archive for reading.
r, err := zip.OpenReader("testdata/readme.zip")
if err != nil {
        log.Fatal(err)
}
defer r.Close()

// Iterate through the files in the archive,
// printing some of their contents.
for _, f := range r.File {
        fmt.Printf("Contents of %s:\n", f.Name)
        rc, err := f.Open()
        if err != nil {
                log.Fatal(err)
        }
        _, err = io.CopyN(os.Stdout, rc, 68)
        if err != nil {
                log.Fatal(err)
        }
        rc.Close()
        fmt.Println()
}
Contents of README:
This is the source code repository for the Go programming language.

func NewReader

func NewReader(r io.ReaderAt, size int64) (*Reader, error)

NewReader returns a new Reader reading from r, which is assumed to have the given size in bytes.
NewReader根据r返回一个新的Reader,它被假定为具有给定的字节大小。

func (*Reader) RegisterDecompressor

func (z *Reader) RegisterDecompressor(method uint16, dcomp Decompressor)

RegisterDecompressor registers or overrides a custom decompressor for a specific method ID. If a decompressor for a given method is not found, Reader will default to looking up the decompressor at the package level.
RegisterDecompressor注册或覆盖指定方法的自定义解压缩程序。如果找不到给定方法的解压缩程序,则Reader将默认在包级别继续查找。

type Writer

Writer implements a zip file writer.
Writer实现了向zip文件的写入操作。

type Writer struct {
        // contains filtered or unexported fields
}

示例

// Create a buffer to write our archive to.
buf := new(bytes.Buffer)

// Create a new zip archive.
w := zip.NewWriter(buf)

// Add some files to the archive.
var files = []struct {
        Name, Body string
}{
        {"readme.txt", "This archive contains some text files."},
        {"gopher.txt", "Gopher names:\nGeorge\nGeoffrey\nGonzo"},
        {"todo.txt", "Get animal handling licence.\nWrite more examples."},
}
for _, file := range files {
        f, err := w.Create(file.Name)
        if err != nil {
                log.Fatal(err)
        }
        _, err = f.Write([]byte(file.Body))
        if err != nil {
                log.Fatal(err)
        }
}

// Make sure to check the error on Close.
err := w.Close()
if err != nil {
        log.Fatal(err)
}
这个例子运行后不会产生任何东西。
如果你把buf := new(bytes.Buffer)换成buf,_ := os.Create("a.zip"),
就会出现一个a.zi包,里面含有代码中创建的三个文本文件。

func NewWriter

func NewWriter(w io.Writer) *Writer

NewWriter returns a new Writer writing a zip file to w.
NewWriter返回一个新的Writer以向w写入zip文件。

func (*Writer) Close

func (w *Writer) Close() error

Close finishes writing the zip file by writing the central directory. It does not (and cannot) close the underlying writer.
Close停止zip文件的写入操作。它无法关闭底层的writer。

func (*Writer) Create

func (w *Writer) Create(name string) (io.Writer, error)

Create adds a file to the zip file using the provided name. It returns a Writer to which the file contents should be written. The name must be a relative path: it must not start with a drive letter (e.g. C:) or leading slash, and only forward slashes are allowed. The file's contents must be written to the io.Writer before the next call to Create, CreateHeader, or Close.
Create将给定名称的文件添加到zip。它返回一个进行写入操作的Writer。该名称必须是相对路径:不能以驱动器号(例如C :)或前导斜杠开头,并且只允许正斜杠。 在下一次调用Create,CreateHeader或Close之前,文件的内容必须写入io.Writer。

func (*Writer) CreateHeader

func (w *Writer) CreateHeader(fh *FileHeader) (io.Writer, error)

CreateHeader adds a file to the zip file using the provided FileHeader for the file metadata. It returns a Writer to which the file contents should be written.
CreateHeader使用提供的FileHeader为元数据对zip进行文件添加。它返回执行写入操作的Writer。

The file's contents must be written to the io.Writer before the next call to Create, CreateHeader, or Close. The provided FileHeader fh must not be modified after a call to CreateHeader.
在下一次调用Create,CreateHeader或Close之前,文件的内容必须写入io.Writer。在调用CreateHeader之后,fh不能被修改。

func (*Writer) Flush

func (w *Writer) Flush() error

Flush flushes any buffered data to the underlying writer. Calling Flush is not normally necessary; calling Close is sufficient.
Flush刷新任何缓冲的数据到底层的writer。调用Flush通常不是必需的;调用Close已足够。

func (*Writer) RegisterCompressor

func (w *Writer) RegisterCompressor(method uint16, comp Compressor)

RegisterCompressor registers or overrides a custom compressor for a specific method ID. If a compressor for a given method is not found, Writer will default to looking up the compressor at the package level.
RegisterCompressor为指定方法注册或覆盖自定义压缩器。如果找不到给定方法的压缩程序,则Writer将默认在包级别继续查找。

示例

package main

import (
	"archive/zip"
	"bytes"
	"compress/flate"
	"io"
)

func main() {
	// Override the default Deflate compressor with a higher compression level.

	// Create a buffer to write our archive to.
	buf := new(bytes.Buffer)

	// Create a new zip archive.
	w := zip.NewWriter(buf)

	// Register a custom Deflate compressor.
	w.RegisterCompressor(zip.Deflate, func(out io.Writer) (io.WriteCloser, error) {
		return flate.NewWriter(out, flate.BestCompression)
	})

	// Proceed to add files to w.
}

func (*Writer) SetOffset

func (w *Writer) SetOffset(n int64)

SetOffset sets the offset of the beginning of the zip data within the underlying writer. It should be used when the zip data is appended to an existing file, such as a binary executable. It must be called before any data is written.
SetOffset设置底层writer zip数据开始的偏移量。应将zip数据附加到现有文件(如二进制可执行文件)时使用。必须在写入任何数据之前调用。