How to use Delphi XE TEncoding to save Cyrillic or ShiftJis text to a file?

I am trying to save some lines of text in an encoding different from my system, such as Cyrillic, to TFileStream using Delphi XE. However, I can not find a sample code to create an encoded file?

I tried to use the same code as TStrings.SaveToStream, but I'm not sure that I implemented it correctly (for example, the WriteBom part) and would like to know how it will be done elsewhere. Here is my code:

FEncoding := TEncoding.GetEncoding(1251);
FFilePool := TObjectDictionary<string,TFileStream>.Create([doOwnsValues]);

//...

procedure WriteToFile(const aFile, aText: string);
var
  Preamble, Buffer: TBytes;
begin
  // Create the file if it doesn't exist
  if not FFilePool.ContainsKey(aFile) then
  begin
    // Create the file
    FFilePool.Add(aFile, TFileStream.Create(aFile, fmCreate));
    // Write the BOM
    Preamble := FEncoding.GetPreamble;
    if Length(Preamble) > 0 then
     FFilePool[aFile].WriteBuffer(Preamble[0], Length(Preamble));
  end;
  // Write to the file
  Buffer := FEncoding.GetBytes(aText);
  FFilePool[aFile].WriteBuffer(Buffer[0], Length(Buffer));
end;

Thanks in advance.

+3
source share
2 answers

If I understand it is quite simple. Declare AnsiString with an affinity for Cyrillic 1251:

type
  // The code page for ANSI-Cyrillic is 1251
  CyrillicString = type AnsiString(1251);

Then assign the Unicode string to one of the following:

var
  UnicodeText: string;
  CyrillicText: CyrillicString;
....
  CyrillicText := UnicodeText;

CyrillicText :

if Length(CyrillicText)>0 then
  Stream.WriteBuffer(CyrillicText[1], Length(CyrillicText));

ANSI- .

+2

, ; : Unicode (SL) ANSI :

procedure SaveCyrillic(SL: TStrings; Stream: TStream);
var
  CyrillicEncoding: TEncoding;

begin
  CyrillicEncoding := TEncoding.GetEncoding(1251);
  try
    SL.SaveToStream(Stream, CyrillicEncoding);
  finally
    CyrillicEncoding.Free;
  end;
end;
+4

Source: https://habr.com/ru/post/1788252/


All Articles