delphi - 无法使用 UTF-8 编码

标签 delphi delphi-2010

我使用此代码加载文本文件(我的文件编码是 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/

相关文章:

Delphi 和 Windows 登录事件

delphi - Delphi 2010 RTTI:如何集成/探索包含自定义属性的枚举

delphi - Async InputQuery 不处理“取消”按钮

delphi - 缩写进度条

c# - 防篡改表

arrays - 如何在 Delphi 中将一个数组 append 到另​​一个相同类型的数组?

delphi - 是否可以从 Windows 服务运行隐藏的控制台应用程序?

delphi - 如何检测 DBGrid 或 ClientDataset 中的用户在运行时删除了单元格中的数据?

delphi - Delphi XE 中有带标题的虚拟列表框吗?

delphi - Delphi-2010 中仍然需要 FastShareMem 吗?