Interacting with the local file system is essential for saving and loading application data, configurations, and user files.
1. Simple Text File I/O (Traditional Approach)
For basic reading and writing of simple text files, Object Pascal uses traditional file I/O procedures. This approach is straightforward but less flexible than using streams.
A. Writing to a Text File
procedure WriteSimpleTextFile(const FileName: String);
var
DataFile: TextFile; // Declare a TextFile variable
begin
AssignFile(DataFile, FileName); // 1. Link the variable to the physical file name
Rewrite(DataFile); // 2. Open the file for writing (creates new, truncates existing)
try
Writeln(DataFile, 'First line of text.'); // Write a line and a newline character
Write(DataFile, 'Second line without newline.'); // Write text without a newline
finally
CloseFile(DataFile); // 3. Always close the file to flush buffers and release the lock
end;
end;
Resource Management: Similar to objects, file handles must be closed. Using
try...finallyaround the file operations guarantees theCloseFileis executed, even if a runtime error occurs during writing.
B. Reading from a Text File
procedure ReadSimpleTextFile(const FileName: String);
var
DataFile: TextFile;
Line: String;
begin
AssignFile(DataFile, FileName);
Reset(DataFile); // Open the file for reading (must exist)
try
while not Eof(DataFile) do // Loop while NOT at the End-Of-File marker
begin
Readln(DataFile, Line); // Read a full line of text into the 'Line' variable
Memo1.Lines.Add(Line); // Display the line in a TMemo component
end;
finally
CloseFile(DataFile);
end;
end;
2. Modern I/O with TStream
For complex tasks—such as reading/writing binary data, handling large files, network transfers, or using compression—Delphi utilizes the abstract base class TStream. Streams provide a unified way to handle data regardless of the source or destination.
You typically use descendant classes of TStream:
TFileStream: Used for reading or writing data directly to a local disk file (most common).TMemoryStream: Used for holding data in memory.TStringStream: Used for handling strings as a stream of bytes.
A. Basic TFileStream Operations
// Requires System.Classes in the uses clause
procedure WriteBinaryFile(const FileName: String);
var
MyStream: TFileStream;
Buffer: array[0..3] of Byte;
Data: Integer;
begin
// fmCreate: Creates a new file. fmOpenRead: Opens for reading. fmOpenWrite: Opens for writing.
MyStream := TFileStream.Create(FileName, fmCreate);
try
Data := 123456;
// Write a specific number of bytes from a variable/buffer to the stream
// Syntax: Write(Buffer, Count)
MyStream.Write(Data, SizeOf(Data));
finally
MyStream.Free; // Always free TStream objects
end;
end;
B. Reading from a Stream
The TStream.Position property is the current location within the data, and TStream.Size is the total size.
procedure ReadBinaryFile(const FileName: String);
var
MyStream: TFileStream;
ReadData: Integer;
begin
// fmOpenRead opens the file only for reading
MyStream := TFileStream.Create(FileName, fmOpenRead);
try
MyStream.Position := 0; // Start reading from the beginning of the file
// Read a specific number of bytes from the stream into a variable/buffer
// Syntax: Read(Buffer, Count)
MyStream.Read(ReadData, SizeOf(ReadData));
ShowMessage('Data read: ' + IntToStr(ReadData));
finally
MyStream.Free;
end;
end;
3. Utility Functions (System.IOUtils)
Modern Delphi includes the System.IOUtils unit, which provides easy, one-line functions for common file operations without dealing with streams directly.
- Requires: Adding
System.IOUtilsto the unit’susesclause.
| Function | Purpose |
TFile.Exists(Path) | Checks if a file exists. |
TFile.Delete(Path) | Deletes a file. |
TFile.ReadAllText(Path) | Reads an entire text file into a single string. |
TFile.WriteAllText(Path, Content) | Writes a string to a file, replacing existing content. |
TDirectory.CreateDirectory(Path) | Creates a new folder/directory. |
// Example: Using IOUtils for simple read/write
uses
System.IOUtils; // Must be in the uses clause
procedure TForm1.SaveAndLoadConfig;
var
ConfigText: String;
FileName: String;
begin
FileName := 'c:\temp\appconfig.txt';
// Write content quickly
TFile.WriteAllText(FileName, 'Setting1=ValueA' + sLineBreak + 'Setting2=ValueB');
// Read content quickly
if TFile.Exists(FileName) then
begin
ConfigText := TFile.ReadAllText(FileName);
ShowMessage(ConfigText);
end;
end;
