我使用此代码加载文本文件(我的文件编码是 UTF-8)( How to read a text file that contains 'NULL CHARACTER' in Delphi? ):
uses
IOUtils;
var
s: string;
ss: TStringStream;
begin
s := TFile.ReadAllText('c:\MyFile.txt');
s := StringReplace(s, #0, '', [rfReplaceAll]); //Removes NULL CHARS
ss := TStringStream.Create(s);
try
RichEdit1.Lines.LoadFromStream(ss, TEncoding.UTF8); //UTF8
finally
ss.Free;
end;
end;
但我的问题是 RichEdit1
没有加载整个文本。
这不是因为空字符。这是因为编码的原因。当我使用此代码运行应用程序时,它会加载整个文本:
uses
IOUtils;
var
s: string;
ss: TStringStream;
begin
s := TFile.ReadAllText('c:\MyFile.txt');
s := StringReplace(s, #0, '', [rfReplaceAll]); //Removes NULL CHARS
ss := TStringStream.Create(s);
try
RichEdit1.Lines.LoadFromStream(ss, TEncoding.Default);
finally
ss.Free;
end;
end;
我将 TEncoding.UTF8
更改为 TEncoding.Default
。整个文本已加载,但格式不正确且不可读。
我猜想有些字符是 UTF 8 不支持的。因此,当它想要加载该字符时,加载过程就会停止。
请帮忙。有什么解决方法吗?
****编辑:**
我确定它是 UTF-8
并且是纯文本。这是一个 HTML 源文件。我确信它有空字符,我使用 Notepad++ 看到它们,并且 Richedit.Plainext
的值是 true
最佳答案
您应该将编码赋予 TFile.ReadAllText。之后,您将仅使用 Unicode 字符串,而不必在 RichEdit 中使用 UTF8。
var
s: string;
begin
s := TFile.ReadAllText('c:\MyFile.txt', TEncoding.UTF8);
// normally this shouldn't be necessary
s := StringReplace(s, #0, '', [rfReplaceAll]); //Removes NULL CHARS
RichEdit1.Lines.Text := s;
end;
关于delphi - 无法使用 UTF-8 编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17590914/