需要帮助理解 Stream.Read() [英] Need help understanding Stream.Read()

查看:32
本文介绍了需要帮助理解 Stream.Read()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对逐步将文件读入缓冲区的步骤有些困惑.

I am a little confused as to the steps of reading a file into buffer gradually.

来自 MSDN 文档

public abstract int Read(
    byte[] buffer,
    int offset,
    int count
)

来自 C# 示例

FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
try
{
    int length = (int)fileStream.Length;  // get file length
    buffer = new byte[length];            // create buffer
    int count;                            // actual number of bytes read
    int sum = 0;                          // total number of bytes read

    // read until Read method returns 0 (end of the stream has been reached)
    while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
        sum += count;  // sum is a buffer offset for next reading

我可以说行 fileStream.Read(buffer, sum, length - sum) 读作Read fileStreamsum(偏移量)到 length - sum(要读取的总字节数)到 buffer".好的,所以在开始时,当 sum = 0 时,我将有效地将整个 fileStream 读入缓冲区 1 短,但我认为情况并非如此.也许 Read() 可以将任何可能的内容读入缓冲区?然后返回以便您可以再次Read()?我有点困惑.

can I say that the line fileStream.Read(buffer, sum, length - sum) reads as "Read fileStream from sum (offset) to length - sum (total bytes to read) into buffer". OK so at the start, when sum = 0, I will effectively read the whole fileStream into buffer in 1 short, but I think this is not the case. Maybe Read() reads whatever it possibly can into buffer? then returns so that you can Read() it again? I am a little confused.

推荐答案

Read 将读取任何可用的内容(阻塞直到 something 可用)但可能没有足够的数据准备好填充缓冲区开始.

Read will read whatever's available (blocking until something is available) but there may not be enough data ready to fill the buffer to start with.

想象一下通过网络下载数据 - 可能有数兆字节的数据需要下载,但只有部分数据可供下载.所以你需要不断调用 Read() 直到你读了你想要的.

Imagine downloading data over the network - there may be megabytes of data to download, but only some of it is available to start with. So you need to keep calling Read() until you've read as much as you want.

Stream.Read 将读取至多您要求的字节数,但可以轻松读取更少的字节数.不可否认,对于本地文件流,我怀疑它的读取量总是与您要求的一样多,除非文件更短,但一般来说,流并非如此,我不相信它保证即使对于本地文件流.

Stream.Read will read at most the number of bytes you've asked for, but can easily read less. Admittedly for local file streams I suspect it always reads as much as you've asked for unless the file is shorter, but that's not true of streams in general, and I don't believe it's guaranteed even for local file streams.

这篇关于需要帮助理解 Stream.Read()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆