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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?