douzhang3822 2013-12-08 22:09
浏览 66
已采纳

如何使用compress / gzip和archive / tar创建压缩的tar档案?

I'm attempting to create a compressed tar archive using the Go standard library, specifically compress/gzip and archive/tar. I can successfully create a tar archive, but when I try to compress said archive, the resulting tarball can't be decompressed. On OSX, I get "Error 1 - Operation Not Permitted"

To run this code, you'll need a file named foo.txt in the same directory.

package main

import (
    "archive/tar"
    "bytes"
    "compress/gzip"
    "io/ioutil"
    "log"
    "os"
)

func main() {
    var b bytes.Buffer

    // Create a new zip archive.
    w := tar.NewWriter(gzip.NewWriter(&b))

    fi, err := os.Stat("foo.txt")

    if err != nil {
        log.Fatal(err)
    }

    header, err := tar.FileInfoHeader(fi, "")

    if err != nil {
        log.Fatal(err)
    }

    err = w.WriteHeader(header)

    if err != nil {
        log.Fatal(err)
    }

    contents, err := ioutil.ReadFile("foo.txt")

    if err != nil {
        log.Fatal(err)
    }

    _, err = w.Write(contents)

    if err != nil {
        log.Fatal(err)
    }

    err = w.Close()

    // Make sure to check the error on Close.
    err = ioutil.WriteFile("foo.tar.gz", b.Bytes(), 0666)

    if err != nil {
        log.Fatal(err)
    }
}
  • 写回答

1条回答 默认 最新

  • dsfhe34889 2013-12-08 22:31
    关注

    You need to close the underlying gzip writer so that it you are guaranteed all bytes are flushed out to the file. Like so:

        // gzip writer
        gz := gzip.NewWriter(f)
    
        // Create a new tar archive.
        w := tar.NewWriter(gz)
    
        // add things to the tar archive
        // ...
    
        // make sure the gzip writer flushes any pending bytes
        if err = gz.Close(); err != nil {
                log.Fatal(err)
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)