I had an issue where io.Copy did not copy the entire file contents. My code was something like:
fReader := bufio.NewReader(sourcef) fWriter := bufio.NewWriter(destf) n, err := io.Copy(fWriter, fReader) if err != nil { fmt.Println("Error while copying:", err) return } fmt.Println("Copied", n, "bytes.") After searching a bit, I learnt that Writers should be flushed to ensure that all of their contents has been written to the destination. I modified my code as: fReader := bufio.NewReader(sourcef) fWriter := bufio.NewWriter(destf) n, err := io.Copy(fWriter, fReader) if err != nil { fmt.Println("Error while copying:", err) return } // Flush the writer to write remaining bytes in the buffer. err = fWriter.Flush() if err != nil { fmt.Println("Error while flushing writer:", err) } else { fmt.Println("Flushed writer.") } fmt.Println("Copied", n, "bytes.") Now the entire file contents were copied successfully. But I have a couple questions in mind: 1. On searching, I found out in Java, the writers are automatically flushed when the corresponding file descriptor is closed. Even though I had deferred close statements on my source and destination files, the writer was not flushed. Why is the behaviour not present in Go? 2. I saw other usages of io.Copy in my organization's codebase and they have used file descriptors directly in place of readers and writers. Hence no need of flushing. Is there any particular reason why I should use readers and writers and not the file descriptors directly? TIA. -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/9f9fc137-6aae-4760-9824-53aa893bca10%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.