如何使用不带 BOM 的 UTF8 将对象从 TStringList class 保存到文件 (Delphi XE 2)?

How can I save a object from TStringList class to file (Delphi XE 2) with UTF8 without BOM?

当我将对象从 TStringList class 文件内容保存到文件时,文件正确保存为 UTF-8,但默认为 UTF-8 和 BOM。

我的代码是:

myFile := TStringList.Create;
try
  myFile.Text := myData;
  myFile.saveToFile('myfile.dat', TEncoding.UTF8)
finally
  FreeAndNil(myFile);
end;

在示例中,文件 "myfile.dat" 显示为 "UTF-8 BOM" 编码。

如何保存没有BOM的文件?

您可以通过创建自己的编码 class 继承自 TUTF8Encoding 并覆盖 GetPreamble 方法来实现此目的:-

type
  TUTF8EncodingNoBOM = class(TUTF8Encoding)
  public
    function GetPreamble: TBytes; override;
  end;</p>

<p>function TUTF8EncodingNoBOM.GetPreamble: TBytes;
begin
  SetLength(Result, 0);
end;

您只需将 属性 TStrings.WriteBOM 设置为 false

文档告诉我们这一点:

Will cause SaveToStream or SaveToFile to write a BOM.

Set WriteBOM to True to cause SaveToStream to write a BOM (byte-order mark) to the stream and to cause SaveToFile to write a BOM to the file.