在不解壓縮的情況下讀取Tar 檔案內容
為了讀取tar 檔案的內容而不將其解壓縮到磁碟,必須使用tar.Reader 作為單一檔案的io.Reader。實作方式如下:
package main import ( "archive/tar" "fmt" "io" "io/ioutil" "log" "os" "bufio" ) func main() { file, err := os.Open("testtar.tar.gz") if err != nil { fmt.Println("There is a problem with os.Open") } tr := tar.NewReader(file) // Get the next file entry h, _ := tr.Next() // Read the complete content of the file into a byte slice bs, _ := ioutil.ReadAll(tr) // Convert the byte slice to a string contents := string(bs) fmt.Printf("Contents of %s:\n%s", h.Name, contents) }
或者,如果您需要逐行存取文件內容:
s := bufio.NewScanner(tr) // Line reading loop for s.Scan() { l := s.Text() // Perform operations on the line } if err := s.Err(); err != nil { // Handle error }
以上是如何在不解壓縮的情況下讀取Tar檔案的內容?的詳細內容。更多資訊請關注PHP中文網其他相關文章!