问题描述
有一个导出文件的库,但我想捕获文件的内容。我想将一个编写器传递给库,并能够读取编写器写入文件的内容。最终我想扩充库以跳过编写此文件。
这可以用io.Copy或io.Pipe吗?
There's a library that exports a file but I'd like to capture the contents of the file. I'd like to pass a writer to the library and be able to read what the writer wrote to the file. Eventually i want to augment the library to skip writing this file. Is this possible with io.Copy or io.Pipe?
库代码创建一个*文件并将此句柄用作io.Writer。
我尝试使用io.Copy,但只读取了0个字节。
The library code creates a *File and uses this handle as an io.Writer.I tried using io.Copy but only 0 bytes were read.
func TestFileCopy(t *testing.T) {
codeFile, err := os.Create("test.txt")
if err != nil {
t.Error(err)
}
defer codeFile.Close()
codeFile.WriteString("Hello World")
n, err := io.Copy(os.Stdout, codeFile)
if err != nil {
t.Error(err)
}
log.Println(n, "bytes")
}
推荐答案
如果要在写入时捕获字节,请使用, bytes.Buffer
作为第二作者。
If you want to capture the bytes as they are written, use an io.MultiWriter
with a bytes.Buffer
as the second writer.
var buf bytes.Buffer
w := io.MultiWriter(codeFile, &buf)
或者在stdout上查看文件:
or to see the file on stdout as it's written:
w := io.MultiWriter(codeFile, os.Stdout)
否则,如果你想要重新读取同一个文件,你需要在写完后回头找:
Otherwise, if you want to re-read the same file, you need to seek back to the start after writing:
codeFile.Seek(0, 0)
这篇关于从io.Writer写的内容中读取内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!