栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

下载文件时如何打印字节?-golang

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

下载文件时如何打印字节?-golang

如果我理解正确,则希望在传输数据时显示读取的字节数。大概保持某种进度条之类的东西。在这种情况下,您可以使用Go的组合数据结构将阅读器或编写器包装在自定义

io.Reader
io.Writer
实现中。

它只是将相应的

Read
Write
调用转发到基础流,同时使用
(int,error)
它们返回的值进行一些其他工作。这是您可以在Go操场上运行的示例。

package mainimport (    "bytes"    "fmt"    "io"    "os"    "strings")// PassThru wraps an existing io.Reader.//// It simply forwards the Read() call, while displaying// the results from individual calls to it.type PassThru struct {    io.Reader    total int64 // Total # of bytes transferred}// Read 'overrides' the underlying io.Reader's Read method.// This is the one that will be called by io.Copy(). We simply// use it to keep track of byte counts and then forward the call.func (pt *PassThru) Read(p []byte) (int, error) {    n, err := pt.Reader.Read(p)    pt.total += int64(n)    if err == nil {        fmt.Println("Read", n, "bytes for a total of", pt.total)    }    return n, err}func main() {    var src io.Reader    // Source file/url/etc    var dst bytes.Buffer // Destination file/buffer/etc    // Create some random input data.    src = bytes.NewBufferString(strings.Repeat("Some random input data", 1000))    // Wrap it with our custom io.Reader.    src = &PassThru{Reader: src}    count, err := io.Copy(&dst, src)    if err != nil {        fmt.Println(err)        os.Exit(1)    }    fmt.Println("Transferred", count, "bytes")}

它生成的输出是这样的:

Read 512 bytes for a total of 512Read 1024 bytes for a total of 1536Read 2048 bytes for a total of 3584Read 4096 bytes for a total of 7680Read 8192 bytes for a total of 15872Read 6128 bytes for a total of 22000Transferred 22000 bytes


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/426858.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号