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

How it works...

The project is not complex. All the interesting stuff happens in btnWriteFile and btnReadFile. To write the file, TStreamWriter is used. TStreamWriter (similar to its counterpart TStreamReader) is a wrapper for a TStream descendant and adds some useful high-level methods to write to the stream. There are a lot of overloaded methods (Write/WriteLine) to allow easy writing to the underlying stream. However, you can access the underlying stream using the BaseStream property of the wrapper. Just after having written the file, the memo reloads the file using the same encoding used to write it and displays it. This is only a fast check for this recipe; you don't need TMemo at all in your real project. The btnReadFile simply opens the file using a stream and passes the stream to TStreamReader which, using the right encoding, will read the file one line at a time (note that text is stored in the .pas file, which is in this case encoded as UTF-8, while by default Delphi .pas files use ASCII encoding).

Now, let's run some checks. Run the program and with the encoding set to ASCII, click on btnWriteFile. The memo will show garbage text, as shown in the following screenshot. This is because we are using the wrong encoding for the data we are writing in the file:

Figure 1.16: Garbage text written to the file using the wrong encoding

Now, select UTF8 from the radio group and retry it. By clicking on btnWriteFile, you will see the correct text in the memo. Try to change the current encoding using ASCII and click on btnReadFile. You will still get garbage text. Why? Because the file has been read with the wrong encoding. You have to know the encoding beforehand to safely read the file's contents. To read the text that we wrote, we have to use the same encoding. Play with other encodings to see the different behavior.