首頁  >  文章  >  後端開發  >  讀取 tar 檔案的內容而不解壓縮到磁碟

讀取 tar 檔案的內容而不解壓縮到磁碟

王林
王林轉載
2024-02-09 22:27:21673瀏覽

读取 tar 文件的内容而不解压到磁盘

php小編草莓今天將為大家介紹一個非常實用的技巧-讀取 tar 檔案的內容而不解壓縮到磁碟。在開發過程中,我們經常需要處理 tar 文件,但解壓縮到磁碟後再讀取會佔用大量的磁碟空間和時間。透過使用PHP的Archive_Tar擴展,我們可以直接讀取 tar 檔案中的內容,避免解壓縮的繁瑣過程,並提高程式碼的效率。接下來,我們一起來了解具體的操作步驟吧!

問題內容

我已經能夠循環遍歷 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
}

以上是讀取 tar 檔案的內容而不解壓縮到磁碟的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除