我已经能够遍历一个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 }