Delphi 判断文本文件的编码格式


本文整理自网络,侵删。

 这里指的文本是用于Windows系统中的扩展名为.txt的文件。

Notepad(记事本)只支持四种格式:ANSI/Unicode/Unicode big endian/UFT-8,在Delphi中如何判断与读取这些不同格式的文本呢?

首先,不同编码的文本,是根据文本的前两个字节来定义其编码格式的。定义如下:

ANSI: 无格式定义;
Unicode: 前两个字节为FFFE;
Unicode big endian: 前两字节为FEFF; 
UTF-8: 前两字节为EFBB; 

知道了各种编码格式的区别,写代码就容易了,以下是我在一个软件中写的处理代码:
 (注意,Delphi的TMemo/TRichEdit只支持ANSI的文本文件,其它编码格式的文件需要
 自行写代码转换成GB2312或BIG5,方能正确显示)


type
  TTextFormat=(tfAnsi,tfUnicode,tfUnicodeBigEndian,tfUtf8);
const
  TextFormatFlag:array[tfAnsi..tfUtf8] of word=($0000,$FFFE,$FEFF,$EFBB); 

function WordLoHiExchange(w:Word):Word;register;
asm
  XCHG AL, AH
end;

{ TextFormat返回文本编码类型,sText未经处理的文本 }
procedure ReadTextFile(const FileName: string;
  var TextFormat: TTextFormat; var sText:string);
var
  w:Word;
  b:Byte;
begin
  with TFileStream.Create(FileName,fmOpenRead or fmShareDenyNone) do
  try
    Read(w,2);
    w:=WordLoHiExchange(w);//因为是以Word数据类型读取,故高低字节互换
    if w = TextFormatFlag[tfUnicode] then
      TextFormat:= tfUnicode
    else if w = TextFormatFlag[tfUnicodeBigEndian] then
      TextFormat:= tfUnicodeBigEndian
    else if w = TextFormatFlag[tfUtf8] then
    begin
      Read(b,1);//这里要注意一下,UFT-8必须要跳过三个字节。
      TextFormat:=tfUtf8;
    end else
    begin
      TextFormat:=tfANSI;
      Position:=0;
    end;
    SetLength(sText,Size-Position);
    ReadBuffer(sText[1],Size-Position);
  finally
    Free;
  end;
end;

相关阅读 >>

Delphi 安卓app的http访问权限

Delphi 对汉字字符串的截取问题

Delphi 取bmp图片宽高

Delphi 通过窗口特定标题锁定窗口

Delphi format 另类用法

Delphi 查询某个字符在字符串出现的位置,支持查找次数

Delphi inttohex 查看字符的十六进制值

Delphi文件分割合并

Delphi selectdirectory 选择文件夹

Delphi 操作前,删除前,覆盖前,询问对话框

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...