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

今天在网上看到一位老兄写的判断记事本保存的文本的四种格式的判断,觉得非常不错。

Notepad (记事本)只支持四种格式: ANSI/Unicode/Unicode big endian/UFT-8 ,在 Delphi 中如何判断与读取这些不同格式的文本呢? 首先,不同编码的文本,是根据文本的前两个字节来定义其编码格式的。
定义如下:
ANSI :          无格式定义;
Unicode        前两个字节为 FFFE
Unicode big endian :  前两字节为 FEFF ; 
UTF-8 :          前两字节为 EFBB ; 

所以读写代码如下:

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;

经过验证ANSI和UTF-8,这个函数完全正确判定文本的格式,但是在读UTF-8文件的时候,会出现汉字乱码。事实上,我们可以利用前两个字节来判断文本类型,而通过Utf8Decode来转换。

把上面的函数简化成一个判定格式的函数,如下,为了简单,返回值使用了String:

function GetTextType(const FileName: string): 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
        Result := 'tfUnicode'
      else if w = TextFormatFlag[tfUnicodeBigEndian] then
        Result:= 'tfUnicodeBigEndian'
      else if w = TextFormatFlag[tfUtf8] then
        Result := 'tfUtf8'
      else
        Result := 'tfANSI';
    finally
      Free;
    end;
end;

感谢 http://www.delphiun.com/Article/Class6/Class7/200604/172.html文章的作者。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值