开发者

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

开发者 https://www.devze.com 2023-02-07 15:47 出处:网络
I\'m trying to save some lines of text in a codepage different from my system\'s such as Cyrillic to a TFileStream using Delphi XE. However I can\'t find any code sample to produce those encoded file

I'm trying to save some lines of text in a codepage different from my system's such as Cyrillic to a TFileStream using Delphi XE. However I can't find any code sample to produce those encoded file ?

I tried using the same code as TStrings.SaveToStream however I'm not sure I implemented it correctly (the WriteBom part for example) and would like to know how it would 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(Preambl开发者_运维技巧e) > 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.


Not sure what example are you looking for; may be the following can help - the example converts unicode strings (SL) to ANSI Cyrillic:

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

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


If I understand it's pretty simple. Declare an AnsiString with affinity for Cyrillic 1251:

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

Then assign your Unicode string to one of these:

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

You can then write CyrillicText to a stream in the traditional manner:

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

There should be no BOM for an ANSI encoded text file.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号