提问人:Franz Andreani 提问时间:9/26/2023 最后编辑:Remy LebeauFranz Andreani 更新时间:9/26/2023 访问量:38
从 TStream 输出中删除 UTF-8 BOM
Remove UTF-8 BOM from TStream output
问:
我正在使用 Delphi 11。我必须使用对象编写一个没有 BOM 的 UTF-8 文件,但使用 会生成一个带有 BOM 的 UTF-8 文件,所以我尝试直接使用编码但没有成功:.csv
TStream
TEncoding.UTF8
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 删除 BOM 使用?TStreamWriter
答:
2赞
Remy Lebeau
9/26/2023
#1
您可以从派生一个新类并重写其虚拟方法以返回一个空字节数组。然后使用该类而不是 或 。SysUtils.TUTF8Encoding
GetPreamble()
TEncoding.UTF8
TEncoding.GetEncoding(65001)
type
TUTF8EncodingNoBOM = class(TUTF8Encoding)
public
function GetPreamble: TBytes; override;
end;
function TUTF8EncodingNoBOM.GetPreamble: TBytes;
begin
Result := nil;
end;
function TfMain.generateCsvFile(pathname : String ; outStr : String; create : boolean; append: boolean; close: boolean) : Boolean;
var
...
UTF8withoutBOM: TEncoding;
begin
Result := False;
UTF8withoutBOM := TUTF8EncodingNoBOM.Create;
try
...
finally
UTF8withoutBOM.Free;
end;
end;
附带说明:您需要返回的对象,否则它将被泄露。Free()
TEncoding
TEncoding.GetEncoding()
评论