golang的緩衝io簡單的使用

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

地址:https://github.com/polaris1119/The-Golang-Standard-Library-by-Example/blob/master/chapter01/01.4.md

上面的地址介紹了基本的使用,以及在readslice的坑上面做瞭解釋。

使用的情境中代碼如下,mapreduce中對檔案根據map數分塊:

// 執行mapreduce前會先將分塊來進行處理func (mr *MapReduce) Split(fileName string) {fmt.Printf("Split %s\n", fileName)infile, err := os.Open(fileName)if err != nil {log.Fatal("Split: ", err)}defer infile.Close()// 返迴文件的基本資料fi, err := infile.Stat()if err != nil {log.Fatal("Split: ", err)}// 返迴文件的大小size := fi.Size()// 得到檔案每塊的大小,按照map數來分塊nchunk := size / int64(mr.nMap)nchunk += 1//kjv12.txt-0outfile, err := os.Create(MapName(fileName, 0))if err != nil {log.Fatal("Split: ", err)}//緩衝的io的寫操作writer := bufio.NewWriter(outfile)m := 1i := 0//一塊一塊的進行讀取;建立一個讀取檔案的scannerscanner := bufio.NewScanner(infile)// 存在資料就會一直掃描下去for scanner.Scan() {if int64(i) > nchunk*int64(m) {// 清除原來的緩衝writer.Flush()outfile.Close()// 建立第二個writeoutfile, err = os.Create(MapName(fileName, m))writer = bufio.NewWriter(outfile)m += 1}// 一行一行的讀取資料line := scanner.Text() + "\n"writer.WriteString(line)i += len(line)}writer.Flush()outfile.Close()}

  

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.