The TStream Class in Delphi

Format
mla apa chicago
Your Citation
Gajic, Zarko. "The TStream Class in Delphi." ThoughtCo, Aug. 23, 2016, thoughtco.com/tstream-class-in-delphi-4077896. Gajic, Zarko. (2016, August 23). The TStream Class in Delphi. Retrieved from https://www.thoughtco.com/tstream-class-in-delphi-4077896 Gajic, Zarko. "The TStream Class in Delphi." ThoughtCo. https://www.thoughtco.com/tstream-class-in-delphi-4077896 (accessed October 23, 2017).
Faster download
John Lamb/DigitalVision/Getty Images

What Is a Stream? TStream?

A stream is what its name suggests: a flowing "river of data". A stream has a beginning, an end, and you're always somewhere in between of these two points.

Using Delphi's TStream objects you can read from or write to various kinds of storage media, such as disk files, dynamic memory, and so on.

What Data Can a Stream Contain?

A stream can contain anything you like, in the order you like.

In the example project accompanying this article, fixed-size records are used for simplicity purposes, but you can write any mix of variable-sized data to a stream. Remember however, that _you_ are responsible for the householding. There is no way Delphi can "remember" what kind of data are in a stream, or in what order!

Streams Versus Arrays

Arrays have the disadvantage of having a fixed size that must be known at compile time. Ok, you can use dynamic arrays.

A stream on the other hand, can grow up to the size of available memory, which is considerably large size on today's systems, without any "householding" chores.

A stream cannot be indexed, as an array can. But as you'll see below, "walking" up and down a stream is very easy.

Streams can be saved/loaded to/from files in one simple operation.

Flavors of Streams

TStream is the base (abstract) class type for stream objects. Being abstract means that TStream should never be used as such, but only in it's descendant forms.

For streaming any kinds of information, choose a descendant class according to the specific data and storage needs. For example: 

    • TFileStream (for working with files)
    • TMemoryStream (for working with a memory buffer)
    • TStringStream (for manipulating in-memory strings)
    • TBlobStream (for working with BLOB fields)
    • TWinSocketStream (for reading and writing over a socket connection)
    • TOleStream (for using a COM interface to read and write)

    As you'll see, TmemoryStream and TFileStream are remarkably interchangeable and compatible.

    Download sample project!