使用golang阅读tar文件的内容而不解压
问题描述:
我已经能够遍历tar文件中的文件,但我坚持如何以字符串形式读取这些文件的内容。我想知道如何以字符串形式打印文件的内容?使用golang阅读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
}
答
与一些帮助官方网站这是我以前的意图。应特别关注从字节到字符串转换的底部。
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()
}
}
+0
请检查我的答案上面的一个更简单的方法来阅读整个事情的一个字符串 –
这会读取,但不会返回正确类型的内容,它只是uint8类型的一部分。没有真正的内容。 –
你不能指望读者知道类型。它负责处理其内容。 – AJPennster
@AJPennster你知道任何简单的方法来完成转换。我很困惑如何一个切片元素不返回一行字符串,但还没有一个int。我不知道如何去做转换。 –