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

只谈情不闲聊 提交于 2019-12-07 16:14:14

问题


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(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.


回答1:


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.




回答2:


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;


来源:https://stackoverflow.com/questions/4819406/how-to-use-delphi-xes-tencoding-to-save-cyrillic-or-shiftjis-text-to-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!