Home >Backend Development >Golang >Read the contents of a tar file without extracting to disk
php editor Strawberry will introduce you to a very practical technique today - reading the contents of a tar file without decompressing it to disk. During the development process, we often need to process tar files, but decompressing them to disk and then reading them will take up a lot of disk space and time. By using PHP's Archive_Tar extension, we can directly read the contents of the tar file, avoid the tedious process of decompression, and improve the efficiency of the code. Next, let’s learn about the specific steps!
I have been able to loop through the files in a tar file, but I have never figured out how to read the contents of these files as a string. I want to know how to print the contents of a file as a string?
This is my code
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) } }
Just use tar.reader as the io.reader for each file you want to read.
tr := tar.newreader(r) // get the next file entry h, _ := tr.next()
If you need the entire file as a string:
// 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)
If you need to read line by line, this is better:
// 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 }
The above is the detailed content of Read the contents of a tar file without extracting to disk. For more information, please follow other related articles on the PHP Chinese website!