首頁 >後端開發 >Golang >如何在不解壓縮的情況下讀取Tar檔案的內容?

如何在不解壓縮的情況下讀取Tar檔案的內容?

Linda Hamilton
Linda Hamilton原創
2024-11-30 15:37:111036瀏覽

How Can I Read the Contents of a Tar File Without Decompression?

在不解壓縮的情況下讀取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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn