Delphi Cookbook
上QQ阅读APP看书,第一时间看更新

Getting ready

In the good old Pascal days, there was a set of functions to handle the I/O (Assign, Reset, Rewrite, Close, and many more). Now, we have a bunch of classes. All Delphi streams inherit from TStream and can be used as the internal stream of one of the adapter classes (by adapter, I mean an implementation of the Adapter, or Wrapper, design patterns from the Gang of Four (GoF) famous book about design patterns).

There are 10 fundamental types of streams:

    
      
        

Class           Use
System.Classes.TBinaryWriter           Writer for binary data
System.Classes.TStreamWriter           Writer for characters to a stream
System.Classes.TStringWriter           Writer for a string
System.Classes.TTextWriter           Writer of a sequence of characters; it is an abstract class
System.Classes.TWriter           Writes component data to an associated stream
System.Classes.TReader           Reads component data from an associated stream
System.Classes.TStreamReader           Reader for stream of characters
System.Classes.TStringReader           Reader for strings
System.Classes.TTextReader           Reader for sequence of characters; it is an abstract class
System.Classes.TBinaryReader           Reader for binary data

 

You can check out the complete list and their intended uses on the Embarcadero website at http://docwiki.embarcadero.com/RADStudio/en/Streams,_Reader_and_Writers.

As Joel Spolsky says, You can no longer pretend that plain text is ASCII. So, while we write streams, we have to pay attention to the encoding our text uses and the encoding our counterpart is waiting for.

One of the most frequent necessities is to efficiently read and write a text file using the correct encoding:

"The Single Most Important Fact About Encodings... It does not make sense to have a string without knowing what encoding it uses. You can no longer stick your head in the sand and pretend that 'plain' text is ASCII."
– Joel Spolsky

The point Joel is making is that the content of a string doesn't know about the type of character encoding it uses.

When you think about file handling, ask yourself—Could this file become 10 MB? And 100 MB? And 1 GB? How will my program behave in that case? Handling a file one line at time and not loading all the file contents in memory is usually good insurance for these cases. A stream of data is a good way to do this. In this recipe, you'll see the practical utilization of streams, stream writers, and stream readers.