Read contents of tar file without unzipping to disk

后端 未结 2 555
暗喜
暗喜 2020-12-19 14:11

I have been able to loop through the files in a tar file, but I am stuck on how to read the contents of those files as string. I would like to know how to print the contents

2条回答
  •  醉梦人生
    2020-12-19 14:38

    Just use the tar.Reader as an 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 whole 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, then this would be 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
    }
    

提交回复
热议问题