无法使用UTF-8编码

Sky*_*Sky 3 delphi delphi-2010

我使用这段代码加载一个文本文件(我的文件编码是UTF-8)(如何在Delphi中读取包含'NULL CHARACTER'的文本文件?):

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;
Run Code Online (Sandbox Code Playgroud)

但我的问题是,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;
Run Code Online (Sandbox Code Playgroud)

我换TEncoding.UTF8TEncoding.Default.加载了整个文本,但它的格式不正确,并且不可读.

我猜有些字符是UTF 8不支持的.因此,加载过程在想要加载该char时停止.

请帮忙.任何解决方法?

****编辑:**

我确定它UTF-8和纯文本.这是一个HTML源文件.我确定它有空字符我看到它们使用Notepad ++而且值Richedit.Plainexttrue

Uwe*_*abe 14

您应该将编码提供给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;
Run Code Online (Sandbox Code Playgroud)

  • 如果它解决了您的问题,您应该接受答案. (4认同)