带有缓冲的读写拷贝IO === 带有缓存读取文件 ~~~ package main import ( "bufio" "fmt" "io" "os" ) func main() { // 获得文件句柄 file, e := os.OpenFile("./test.file", os.O_RDONLY, 0666) if e != nil { panic(e.Error()) } // 创建读取器 reader := bufio.NewReader(file) // 创建缓冲区 bytes := make([]byte, 1024) // 1024为1K for { n, e := reader.Read(bytes) fmt.Printf("%s",bytes[:n]) if e == io.EOF{ break } } } ~~~ # 注意这里只说一次 ``` n, e := reader.Read(bytes) fmt.Printf("%s",bytes[:n]) bytes可能没有装满 就这样才能不然会出bug ``` 带有缓冲写入 ~~~ func write() { // 获取文件句柄 (O_CREATE) 不存在就创建 (O_WRONLY) 写入 (O_APPEND) 追加 file, e := os.OpenFile("./new.text", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 00666) defer file.Close() if e != nil { panic(e.Error()) } // 创建写出器 writer := bufio.NewWriter(file) _, e = writer.Write([]byte("hello")) if e != nil { fmt.Printf(e.Error()) } writer.Flush() //倒干缓冲区 } ~~~ ### copy 同步 ~~~ func copy() { old, e := os.OpenFile("./test.mp4", os.O_RDONLY, 00666) new, e := os.OpenFile("./new.mp4", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 00666) if e != nil { panic(e.Error()) } reader := bufio.NewReader(old) writer := bufio.NewWriter(new) bytes := make([]byte, 1024) for { _, e := reader.Read(bytes) if e == io.EOF { break }else{ writer.Write(bytes) } } defer func() { writer.Flush() old.Close() new.Close() }() } ~~~ 共同争抢资源有可能是乱序不推荐(这个根本不能用,乱序的!!!) ~~~ /** * Created by GoLand * User: dollarkiller * Date: 19-6-10 * Time: 下午9:20 * */ package main import ( "bufio" "context" "io" "os" "sync" ) func main() { ch := make(chan []byte,1024) ctx, cancel := context.WithCancel(context.TODO()) var wg sync.WaitGroup wg.Add(2) go read(ch,cancel,&wg) go write(ctx,ch,&wg) wg.Wait() //time.Sleep(time.Second * 3) } func read(ch chan []byte,cancelFunc context.CancelFunc,wg *sync.WaitGroup) { file, e := os.OpenFile("./test.file", os.O_RDONLY, 00666) defer func() { file.Close() }() if e != nil { panic(e.Error()) } reader := bufio.NewReader(file) bytes := make([]byte, 1024) for { _, e := reader.Read(bytes) ch <- bytes if e == io.EOF { cancelFunc() break } } wg.Done() } func write(ctx context.Context,ch chan []byte,wg *sync.WaitGroup) { file, e := os.OpenFile("./new.file", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 00666) defer func() { file.Close() }() if e != nil { panic(e.Error()) } writer := bufio.NewWriter(file) forloop: for { select { case <-ch: writer.Write(<-ch) case <-ctx.Done(): break forloop } } writer.Flush() wg.Done() } ~~~