需要帮助了解Stream

需要帮助了解Stream

本文介绍了需要帮助了解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
)

通过

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



我可以说,该行的 <$抵消C $ C> fileStream.Read(缓冲,总和,长度 - 总和) 读作 FILESTREAM (补偿),以长度 - 总和(总读取字节)为缓存 。行,所以在一开始,当 = 0,我将有效地读取整个FILESTREAM到缓冲区1短,但我觉得这是不是这样的。也许阅读()读不管它可能可以进入缓冲区?然后返回,这样就可以阅读()再次吗?我有点困惑。

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 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.

想象通过网络下载数据 - 有可能是兆数据下载,而只是它的一些可下手。所以,你需要不断的打电话阅读(),直到你读过只要你想尽可能多。

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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 16:19