Delphi - TStringList Save/Load 流编码

Delphi - TStringList Save/Load to stream encoding

我在项目中经常与 TStringListTMemeorySteam 合作。

  msTmp := TMemoryStream.Create;
  try
     lTemp.SaveToStream(msTmp, TEncoding.Unicode);
  finally
    msTmp.Free;
  end;
  .....
  lTemp := TStringList.Create;
  try
     lTemp.LoadFromFile(msTmp, TEncoding.Unicode);
  finally
    lTemp.Free;
  end;

我如何告诉 LoadFromStream()SaveToStream() 流在我的项目中默认为 UTF-16 编码,而无需在每次调用中包括编码类型。 所以我只能调用 LoadFromStream(msTmp),它将以 UTF-16 编码加载。

看看 TStrings.DefaultEncoding 属性.

The default encoding for the current object.

DefaultEncoding is used when the nil encoding is specified in a call to LoadFromStream or SaveToStream.

By default, DefaultEncoding is set to Default. The user can change DefaultEncoding if another default encoding is desired for LoadFromStream or SaveToStream.

但是,请注意 TStrings.Encoding 属性:

Character encoding determined during reading from a stream or file.

Encoding is a read-only property that contains the value of the character encoding detected when the LoadFromStream or LoadFromFile methods are called. If a file or stream does not contain a BOM (the encoding value cannot be detected) then Encoding is set to the value specified in the DefaultEncoding property.

Encoding is used in the SaveToStream and SaveToFile methods.

If the Encoding parameter [of LoadFromStream] is not given, then the strings are loaded using the appropriate encoding. The value of the encoding is obtained by calling the GetBufferEncoding routine of the TEncoding class. LoadFromStream then saves the value of the encoding in the Encoding property, to be used if the stream is saved.

因此,只要不调用LoadFrom...(),就可以将DefaultEncoding设置为TEncoding.Unicode,然后调用SaveTo...()而不指定[=]的值17=] 参数.

但是,一旦您调用 LoadFrom...()Encoding 属性 将优先于 DefaultEncoding 属性 进行后续调用 SaveTo...() .只要文件没有 BOM,Encoding 属性 就会匹配 DefaultEncoding 属性。但如果遇到非UTF16LE BOM,则一切皆有可能。

要确保始终使用 TEncoding.Unicode,您应该继续使用 LoadFrom...()SaveTo...()Encoding 参数,这就是它们存在的原因。它们具有第一优先级,当 input/output 编码未明确说明时,(Default)Encoding 属性是后备。