Stream large files
Stream large files
Streaming processes bytes incrementally instead of loading a whole file into memory. io.Copy transfers until EOF or an error and reports the byte count. A real source can be large, but this lab uses a tiny synthetic file so you can inspect the result safely.
package main
import ( "fmt" "io" "os" "path/filepath")
func check(err error) { if err != nil { panic(err) }}func lab() (string, func()) { d, err := os.MkdirTemp("", "bytemind-") check(err) return d, func() { check(os.RemoveAll(d)) }}
func main() { d, cleanup := lab() defer cleanup() check(os.WriteFile(filepath.Join(d, "src"), []byte("abcdef"), 0600)) src, e := os.Open(filepath.Join(d, "src")) check(e) defer func() { check(src.Close()) }() dst, e := os.OpenFile(filepath.Join(d, "dst"), os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) check(e) n, e := io.Copy(dst, src) closeErr := dst.Close() check(e) check(closeErr) b, e := os.ReadFile(filepath.Join(d, "dst")) check(e) fmt.Println(n, string(b))}Check the transfer and close errors separately. A failed copy can leave a partial destination; a production system may write to a temporary file and promote it only after success, subject to OS rename and durability rules. ReadFile here only verifies the tiny fixture. io.Copy may use optimized WriterTo or ReaderFrom methods rather than an explicit buffer.
Expected output:
6 abcdefLimit the bytes processed
package main
import ( "bytes" "fmt" "io" "os" "path/filepath")
func check(err error) { if err != nil { panic(err) }}func lab() (string, func()) { d, err := os.MkdirTemp("", "bytemind-") check(err) return d, func() { check(os.RemoveAll(d)) }}
func main() { d, cleanup := lab() defer cleanup() check(os.WriteFile(filepath.Join(d, "src"), []byte("abcdef"), 0600)) f, e := os.Open(filepath.Join(d, "src")) check(e) defer func() { check(f.Close()) }() var out bytes.Buffer n, e := io.CopyN(&out, f, 3) check(e) fmt.Println(n, out.String())}CopyN requests exactly N bytes and returns an error if it cannot copy that many. It does not establish that the entire file has only N bytes. A byte limit is not a time limit. Buffer is bounded here by N; for arbitrary large files write to a bounded or streaming destination.
Expected output:
3 abcTry it locally
Write "abc" in a temporary source file, stream it to io.Discard and print the count and success.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Files and paths 06: Stream large files
Check the lesson objective before moving on.
What does io.Copy return?
What can remain after a failed file copy?