gpt4 book ai didi

Delphi - TStringList 保存/加载到流编码

转载 作者:行者123 更新时间:2023-12-03 15:08:53 25 4
gpt4 key购买 nike

我在项目中经常使用 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...() ,可以设置DefaultEncodingTEncoding.Unicode然后调用SaveTo...()不指定 Encoding 的值参数。

但是,一旦你调用LoadFrom...()Encoding属性优先于 DefaultEncoding属性用于后续调用 SaveTo...() 。只要文件未经过 BOM 编辑,Encoding属性将匹配 DefaultEncoding属性(property)。但如果遇到非 UTF16LE BOM,一切就都失败了。

确保 TEncoding.Unicode始终使用,您应该继续使用Encoding LoadFrom...()的参数和SaveTo...() ,这就是它们存在的原因。他们优先考虑 (Default)Encoding当未明确说明输入/输出编码时,属性是后备。

关于Delphi - TStringList 保存/加载到流编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37957409/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com