delphi2007 读取得unicode文本


本文整理自网络,侵删。

 

const

utf8Head: Array[0..2] of Char = (#239,#$bb,#$bf);
unicodeHead: Array[0..1] of Char = (#255,#$fe);

// read utf8 file
function ReadUtf8File(const filename:string):Utf8String;
var
memoStream:TFileStream;
buf:array of Char;
begin
memoStream:=TFileStream.Create(filename, fmOpenRead);
try
setlength(buf,memoStream.size);
memoStream.ReadBuffer(buf[0], memoStream.size);
//utf-8 file
if (buf[0]=Utf8Head[0]) and (buf[1]=Utf8Head[1]) and (buf[2]=Utf8Head[2]) then
begin
FillChar(buf, SizeOf(buf), #0);
memoStream.Seek(3,soFromBeginning);
setlength(buf,memoStream.size-3);
memoStream.ReadBuffer(buf[0], memoStream.size-3);
result:=Utf8String(buf);
exit;
end else result:=UTF8Encode(WideString('File is not utf8-file'));
finally
memoStream.Free;
end;
end;

// read unicode file
function ReadUnicodeFile(const filename:string):WideString;
var
memoStream:TFileStream;
buf:array of Char;
begin
memoStream:=TFileStream.Create(filename, fmOpenRead);
try
setlength(buf,memoStream.size);
memoStream.ReadBuffer(buf[0], memoStream.size);
//unicode file
if (buf[0]=UnicodeHead[0]) and (buf[1]=UnicodeHead[1]) then
begin
FillChar(buf, SizeOf(buf), #0);
memoStream.Seek(2,soFromBeginning);
setlength(buf,memoStream.size-2);
memoStream.ReadBuffer(buf[0], memoStream.size-2);
result:=PWideChar(buf);
exit;
end else result:=WideString('File is not unicode-file');
finally
memoStream.Free;
end;
end;

procedure WriteUnicodeFile(const filename:string;mem:Widestring);
var
wms:TMemoryStream;
begin
wms:=TMemoryStream.Create;
wms.WriteBuffer(unicodeHead,length(unicodeHead));
wms.WriteBuffer(PChar(mem)^,length(mem)*2);
wms.SaveToFile(filename);
wms.Free;
end;

procedure WriteUtf8File(const filename:string;mem:Utf8String);
var
wms:TMemoryStream;
begin
wms:=TMemoryStream.Create;
wms.WriteBuffer(utf8Head,length(utf8Head));
wms.WriteBuffer(pchar(mem)^,length(Ansistring(mem)));
wms.SaveToFile(filename);
wms.Free;
end;

相关阅读 >>

Delphi 如何识别应用程序没有响应

Delphi twebbrowser get html source after ajax load

Delphi xe5 android实现繁体字到简体字的转换函数

Delphi 简单的软件注册demo

Delphi 之 定时器 (ttimer组件)

Delphi 执行dos命令并捕获输出

DelphiDelphi提升进程权限为debug权限

Delphi tadocommand 中文使用说明

Delphi的tfilestream 内存流

Delphi xe 中的字符串生成哈希值(md5 / sha-1 / jenkins)

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



打赏

取消

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

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

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

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

评论

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