从io.Writer写入的内容中读取。

huangapple go评论93阅读模式
英文:

Read contents from what io.Writer writes

问题

有一个库可以导出一个文件,但我想捕获文件的内容。我想传递一个写入器给库,并能够读取写入器写入文件的内容。最终,我想修改库以跳过写入这个文件。使用io.Copy或io.Pipe可以实现这个吗?

库的代码创建了一个*File,并将其作为io.Writer使用。
我尝试使用io.Copy,但只读取了0字节。

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")
}
英文:

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?

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")
}

答案1

得分: 6

如果你想按原样捕获字节流,可以使用io.MultiWriter,并将bytes.Buffer作为第二个写入器。

var buf bytes.Buffer
w := io.MultiWriter(codeFile, &buf)

或者如果你想在写入时将文件内容显示在标准输出中:

w := io.MultiWriter(codeFile, os.Stdout)

否则,如果你想重新读取同一个文件,在写入后需要将文件指针定位回开头:

codeFile.Seek(0, 0)
英文:

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)

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)

huangapple
  • 本文由 发表于 2017年7月27日 20:44:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/45351208.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定