How can I write a Unicode text file in Delphi?
Currently I simply use AssignFile
, RewriteFile
, and Writeln
, but this does not write Unicode characters.
Join Stack Overflow to learn, share knowledge, and build your career.
How can I write a Unicode text file in Delphi?
Currently I simply use AssignFile
, RewriteFile
, and Writeln
, but this does not write Unicode characters.
You shouldn't be using old Pascal I/O at all. That did its job back in the 80s but is very obsolete today.
This century, you can use the TStringList
. This is very commonly used in Delphi. For instance, VCL controls use TStrings
to access a memo's lines of text and a combo box's or list box's items.
var SL := TStringList.Create;
try
SL.Add('∫cos(x)dx = sin(x) + C');
SL.Add('¬(a ∧ b) ⇔ ¬a ∨ ¬b');
SL.SaveToFile(FileName, TEncoding.UTF8);
finally
SL.Free;
end;
Fore more advanced needs, you can use a TStreamWriter
:
var SW := TStreamWriter.Create(FileName, False, TEncoding.UTF8);
try
SW.WriteLine('αβγδε');
SW.WriteLine('ωφψξη');
finally
SW.Free;
end;
And for very simple needs, there are the new TFile
methods in IOUtils.pas
:
var S := '⌬ is aromatic.';
TFile.WriteAllText(FileName, S, TEncoding.UTF8); // string (possibly with linebreaks)
var Lines: TArray<string>;
Lines := ['☃ is cold.', '☼ is hot.'];
TFile.WriteAllLines(FileName, Lines, TEncoding.UTF8); // string array
As you can see, all these modern options allow you to specify UTF8 as encoding. If you prefer to use some other encoding, like UTF16, that's fine too.
Just forget about AssignFile
, Reset
, Rewrite
, Append
, CloseFile
etc.
TFileStream
instead. It's existed for more than 2 decades now. You're using file I/O that is from Turbo Pascal 1. Even using aTStringList.SaveToFile
would be better when dealing with text files. – Ken White Nov 28 '20 at 22:01TStreamWriter
instead. – Remy Lebeau Nov 28 '20 at 22:16