Read contents of tar file without unzipping to disk

后端 未结 2 565
暗喜
暗喜 2020-12-19 14:11

I have been able to loop through the files in a tar file, but I am stuck on how to read the contents of those files as string. I would like to know how to print the contents

2条回答
  •  感情败类
    2020-12-19 14:54

    With some help from the official site this is what I had intended previously. Special focus should be turned to the bottom where the conversion from bytes to string is made.

    package main
    
    import (
        "archive/tar"
        "fmt"
        "io"
        "log"
        "os"
        "bytes"
        "compress/gzip"
    )
    
    func main() {
    
        file, err := os.Open("testtar.tar.gz")
    
        archive, err := gzip.NewReader(file)
    
        if err != nil {
            fmt.Println("There is a problem with os.Open")
        }
        tr := tar.NewReader(archive)
    
        for {
            hdr, err := tr.Next()
            if err == io.EOF {
                break
            }
            if err != nil {
                log.Fatal(err)
            }
    
            fmt.Printf("Contents of %s:\n", hdr.Name)
    
            //Using a bytes buffer is an important part to print the values as a string
    
            bud := new(bytes.Buffer)
            bud.ReadFrom(tr)
            s := bud.String()
            fmt.Println(s)
            fmt.Println()
        }
    
    }
    

提交回复
热议问题