dongshi9526 2015-08-14 20:26
浏览 214
已采纳

Golang:为什么compress / gzip Read函数不能读取文件内容?

I made a text file, that I then compressed with gzip. I then run the following go program to read the contents of that compressed file.

package main

import (
    "compress/gzip"
    "fmt"
    "os"
)

func main() {
    handle, err := os.Open("zipfile.gz")
    if err != nil {
        fmt.Println("[ERROR] File Open:", err)
    }
    defer handle.Close()

    zipReader, err := gzip.NewReader(handle)
    if err != nil {
        fmt.Println("[ERROR] New gzip reader:", err)
    }
    defer zipReader.Close()

    var fileContents []byte
    bytesRead, err := zipReader.Read(fileContents)
    if err != nil {
        fmt.Println("[ERROR] Reading gzip file:", err)
    }
    fmt.Println("[INFO] Number of bytes read from the file:", bytesRead)
    fmt.Printf("[INFO] Uncompressed contents: '%s'
", fileContents)
}

The response that I get is the following:

$ go run zipRead.go
[INFO] Number of bytes read from the file: 0
[INFO] Uncompressed contents: ''

Why am I not getting any contents from the file?

I have created zip files on both OS X and Ubuntu. I have build this go program on both OS X and Ubuntu with the same result.

  • 写回答

1条回答 默认 最新

  • donglu1881 2015-08-14 21:00
    关注

    io.Reader.Read will only read up to len(b) bytes. Since your fileContents is nil, its length is 0. Allocate some space for it to read into:

    fileContents := make([]byte, 1024) // Read by 1 KiB.
    bytesRead, err := zipReader.Read(fileContents)
    if err != nil {
        fmt.Println("[ERROR] Reading gzip file:", err)
    }
    fileContents = fileContents[:bytesRead]
    

    If you want to read the whole file, you'll have to either use Read several times, or use things like ioutil.ReadAll (which may be bad for big files).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥15 vba使用jmail发送邮件正文里面怎么加图片
  • ¥15 vb6.0如何向数据库中添加自动生成的字段数据。