在不解压缩到磁盘的情况下读取tar文件的内容 [英] Read contents of tar file without unzipping to disk
本文介绍了在不解压缩到磁盘的情况下读取tar文件的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经能够遍历tar文件中的文件,但是我仍然坚持如何以字符串的形式读取那些文件的内容.我想知道如何将文件内容打印为字符串?
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 of the files as a string?
这是我的下面的代码
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.
Just use the tar.Reader as an io.Reader for each file you want to read.
tr := tar.NewReader(r)
// get the next file entry
h, _ := tr.Next()
如果您需要整个文件作为字符串:
If you need the whole file as a string:
// 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)
如果您需要逐行阅读,那会更好:
If you need to read line by line, then this would be better:
// 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
}
这篇关于在不解压缩到磁盘的情况下读取tar文件的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文