如何判断⽂本⽂件的编码格式?
这⾥指的⽂本是⽤于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:fUtf8] 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;unicode文件格式

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。