在Go中,可以使用"archive/zip"包来压缩目录。以下是一个示例代码:

package main

import (
    "archive/zip"
    "fmt"
    "io"
    "os"
    "path/filepath"
)

func main() {
    dirToZip := "/path/to/directory"
    zipFileName := "compressed.zip"

    // 创建压缩文件
    zipFile, err := os.Create(zipFileName)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer zipFile.Close()

    // 创建zip.Writer
    zipWriter := zip.NewWriter(zipFile)
    defer zipWriter.Close()

    // 遍历目录
    filepath.Walk(dirToZip, func(path string, info os.FileInfo, err error) error {
        if err != nil {
            return err
        }

        // 获取相对路径
        relPath, err := filepath.Rel(dirToZip, path)
        if err != nil {
            return err
        }

        // 创建zip文件头
        header := &zip.FileHeader{
            Name:   relPath,
            Method: zip.Deflate,
        }

        // 设置编码
        header.SetExtra([]byte{0x01, 0x00}) // UTF-8编码

        // 如果是目录,跳过
        if info.IsDir() {
            header.Name += "/"
            _, err = zipWriter.CreateHeader(header)
            if err != nil {
                return err
            }
            return nil
        }

        // 创建zip文件
        writer, err := zipWriter.CreateHeader(header)
        if err != nil {
            return err
        }

        // 打开文件
        file, err := os.Open(path)
        if err != nil {
            return err
        }
        defer file.Close()

        // 复制文件数据到zip文件
        _, err = io.Copy(writer, file)
        if err != nil {
            return err
        }

        return nil
    })

    fmt.Println("Directory compressed successfully!")
}

在上述代码中,我们使用os.Create函数来创建压缩文件,然后使用zip.NewWriter函数创建zip.Writer。之后,我们使用filepath.Walk函数来遍历目录,并为每个文件或目录创建zip文件头。我们还设置了zip文件头的编码为UTF-8。

对于目录,我们只需创建zip文件头,而不必复制文件数据。对于文件,我们使用zipWriter.CreateHeader函数创建zip文件,并使用io.Copy函数将文件数据复制到zip文件中。

最后,我们在终端中使用命令go run main.go来运行程序。如果一切顺利,我们将看到"Directory compressed successfully!"的消息,表示目录已成功压缩。

golang zip压缩目录并设置编码

原文地址: https://www.cveoy.top/t/topic/brfz 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录