doutonghang2761 2017-04-27 04:57
浏览 62
已采纳

如何在Golang的tar文件中放入tar文件

I want to create a tar file and inside that tar file I want to put other tar files.Hierarchy is something like

TopLevelTar.tar.gz
    |-->primary/primary.tar
    |-->secondary/secondaty.tar
    |-->tertiary/tertiary.tar

How can I do it in golag?

  • 写回答

2条回答 默认 最新

  • duancai9010 2017-04-27 09:56
    关注

    I think this might help you. Basically, this solution is creating a tarball from multiple files. You have to simply give path of your files in place of a.go and b.go etc.

    package main
    
    import (
        "archive/tar"
        "compress/gzip"
        "io"
        "log"
        "os"
    )
    
    func addFile(tw *tar.Writer, path string) error {
        file, err := os.Open(path)
        if err != nil {
            return err
        }
        defer file.Close()
        if stat, err := file.Stat(); err == nil {
            // now lets create the header as needed for this file within the tarball
            header := new(tar.Header)
            header.Name = path
            header.Size = stat.Size()
            header.Mode = int64(stat.Mode())
            header.ModTime = stat.ModTime()
            // write the header to the tarball archive
            if err := tw.WriteHeader(header); err != nil {
                return err
            }
            // copy the file data to the tarball
            if _, err := io.Copy(tw, file); err != nil {
                return err
            }
        }
        return nil
    }
    
    func main() {
        // set up the output file
        file, err := os.Create("output.tar.gz")
        if err != nil {
            log.Fatalln(err)
        }
        defer file.Close()
        // set up the gzip writer
        gw := gzip.NewWriter(file)
        defer gw.Close()
        tw := tar.NewWriter(gw)
        defer tw.Close()
        // grab the paths that need to be added in
        paths := []string{
            "a.go",
            "b.go",
        }
        // add each file as needed into the current tar archive
        for i := range paths {
            if err := addFile(tw, paths[i]); err != nil {
                log.Fatalln(err)
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应