来自文件的ReadAll不能按预期工作 [英] ReadAll from File not working as Expected
问题描述
我正在尝试创建一个临时gzip文件并写入该文件.问题是我不了解ReadAll的情况.我希望ReadAll返回写入文件的字节...但是没有.但是File.Stat命令显示确实存在数据.
I am trying to create a temporary gzip file and write to the file. The problem is that I am not understanding what is going on with ReadAll. I expected ReadAll to return the bytes written to the file... however there are none. Yet the File.Stat command shows that there is indeed data.
filename := "test"
file, err := ioutil.TempFile("", filename)
if err != nil {
fmt.Println(err)
}
defer func() {
if err := os.Remove(file.Name()); err != nil {
fmt.Println(err)
}
}()
w := gzip.NewWriter(file)
_, err = w.Write([]byte("hell0"))
if err != nil {
fmt.Println(err)
}
fileInfo, err := file.Stat()
if err != nil {
fmt.Println(err)
}
fileBytes, err := ioutil.ReadAll(file)
if err != nil {
fmt.Println(err)
}
if err := w.Close(); err != nil {
fmt.Println(err)
}
fmt.Println("SIZE1:", fileInfo.Size())
fmt.Println("SIZE2:", len(fileBytes))
这是一个游乐场链接 https://play.golang.org/p/zX8TSCAbRL
为什么没有返回的字节?如何获取返回的字节?
Why are there no returned bytes? How do I get the returned bytes?
推荐答案
在读取文件之前将其关闭.
Close the file before reading it.
来自 gzip的文档:
Write将p的压缩形式写入底层的io.Writer.直到Writer关闭后,才会刷新压缩的字节.
Write writes a compressed form of p to the underlying io.Writer. The compressed bytes are not necessarily flushed until the Writer is closed.
因此,解决方案是在尝试读取字节数之前,同时关闭gzip Writer和基础io.Writer.
The solution therefore is to Close
both the gzip Writer as well as the underlying io.Writer before attempting to read the number of bytes.
func main() {
basename := "test"
file, err := ioutil.TempFile("", basename)
tempFilename := file.Name()
if err != nil {
fmt.Println(err)
}
defer func() {
if err := os.Remove(file.Name()); err != nil {
fmt.Println(err)
}
}()
w := gzip.NewWriter(file)
_, err = w.Write([]byte("hell0"))
if err != nil {
fmt.Println(err)
}
w.Close()
file.Close()
file, err = os.Open(tempFilename)
fileInfo, err := file.Stat()
if err != nil {
fmt.Println(err)
}
fileBytes, err := ioutil.ReadAll(file)
if err != nil {
fmt.Println(err)
}
if err := w.Close(); err != nil {
fmt.Println(err)
}
fmt.Println("SIZE1:", fileInfo.Size())
fmt.Println("SIZE2:", len(fileBytes))
}
在
这篇关于来自文件的ReadAll不能按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!