dplm47571 2017-07-27 12:44
浏览 114
已采纳

从io.Writer编写的内容中读取内容

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条回答 默认 最新

  • douzi1117 2017-07-27 12:47
    关注

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败