我正在使用 Delphi 11。我必须使用
.csv
对象编写一个没有 BOM 的 UTF-8 TStream
文件,但是使用 TEncoding.UTF8
会生成一个带有 BOM 的 UTF-8 文件,所以我尝试使用直接编码没有成功:
function TfMain.generateCsvFile(pathname : String ; outStr : String; create : boolean; append:boolean; close:boolean) : Boolean;
var
//Writer: TStreamWriter;
UTF8withoutBOM: TEncoding;
begin
Result := False;
UTF8withoutBOM := TEncoding.GetEncoding(65001);
try
if create then begin
Writer := TStreamWriter.Create(pathname, False, UTF8WithoutBOM);
end;
if append then begin
Writer.WriteLine(outStr);
Writer.Flush;
Result := True;
end;
if close then begin
Writer.Close;
Writer.Free;
end;
except
on e : Exception do begin
ShowMessage('Errore '+e.Message);
lbConsole.Items.Add('Errore '+e.Message);
end;
end;
end;
有没有办法告诉Delphi使用
TStreamWriter
删除BOM?
您可以从
SysUtils.TUTF8Encoding
派生一个新类并重写其虚拟 GetPreamble()
方法以返回空字节数组。然后使用该类而不是 TEncoding.UTF8
或 TEncoding.GetEncoding(65001)
。
附注:您需要
Free()
TEncoding
返回的 TEncoding.GetEncoding()
对象,否则它将被泄漏。