delphi - 如何使用Delphi XE的TEncoding将西里尔文或ShiftJis文本保存到文件?

标签 delphi unicode delphi-xe codepages

我正在尝试使用 Delphi XE 将与我的系统不同的代码页(例如西里尔文)中的一些文本行保存到 TFileStream。但是我找不到任何代码示例来生成这些编码文件?

我尝试使用与 TStrings.SaveToStream 相同的代码,但是我不确定我是否正确实现了它(例如 WriteBom 部分),并且想知道它在其他地方是如何完成的。这是我的代码:

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;

提前致谢。

最佳答案

不确定您要寻找什么示例;以下内容可能会有所帮助 - 该示例将 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;

关于delphi - 如何使用Delphi XE的TEncoding将西里尔文或ShiftJis文本保存到文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4819406/

相关文章:

c++ - 用什么来替换 std::u16string 的 std::stringstream 和 boost::format ?

python - 使用 Python 读取 RTF 文件时出现欧元符号问题

python - [ :alpha:] in python regex 的简写

delphi - 使用delphi下载iphone网页

delphi - 使用delphi枚举单元的全局方法

c - 如何将 typedef union 翻译成 delphi?

Delphi - 检测我的应用程序是否打开了模式对话框

windows - 如何阻止某个文件夹的访问?

delphi - 如何隐藏 TRibbon 页面?