Hello, Indeed, you need to flush the bufio.Writer for the remaining data to be sent accross. Usually though, you do not need to buffer the input or output at all. In which case, the code is straight forward:
https://play.golang.org/p/F1tMKdsapyX If you do need to buffer though, I would do something along the lines of: https://play.golang.org/p/e5xFL_nUdp5 or even https://play.golang.org/p/3I1J_4zOKL4 I would stringly encourage you to *use* interfaces such as the io.Reader and io.Writer and *not* file descriptors. You will find that they are very easy to work with and make your code much easier to read, test and maintain in the long run. HTH Le mardi 21 mai 2019 09:03:32 UTC+2, Subramanian Sridharan a écrit : > > 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/83a24007-df16-489d-b3cb-5fdd3f14bacd%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.