go - 读取 tar 文件的内容而不解压缩到磁盘

标签 go tar

我已经能够遍历 tar 文件中的文件,但我对如何将这些文件的内容作为字符串读取感到困惑。我想知道如何将文件内容打印为字符串?

下面是我的代码

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)
    }
}

最佳答案

只需将 tar.Reader 用作您要阅读的每个文件的 io.Reader。

tr := tar.NewReader(r)

// get the next file entry 
h, _ := tr.Next() 

如果你需要整个文件作为一个字符串:

// read the complete content of the file h.Name into the bs []byte
bs, _ := ioutil.ReadAll(tr)

// convert the []byte to a string
s := string(bs)

如果你需要逐行阅读,那么这样会更好:

// create a Scanner for reading line by line
s := bufio.NewScanner(tr)

// line reading loop
for s.Scan() {

  // read the current last read line of text
  l := s.Text()

  // ...and do something with l

}

// you should check for error at this point
if s.Err() != nil {
  // handle it
}

关于go - 读取 tar 文件的内容而不解压缩到磁盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42564146/

相关文章:

go - 接口(interface)声明差异

rest - 本地依赖的 GCF 部署

concurrency - sync.WaitGroup 不等待

python - Tornado 如何使用管道异步发送数据到客户端?

linux - Raspberry Pi 和 RetroPie 发行版加 LCD

node.js - 解压/解压缩到 Node 中的流

javascript - zserge/lorca ui.Eval 没有返回值

pointers - Golang 通过引用结构成员值传递变量

scripting - 一步以编程方式提取 tar.gz(在带有 7-Zip 的 Windows 上)

python - flask send_file 不适用于 tar.gz 文件