我已经能够遍历 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/