给客户做了一个批量识别图像并合成双层pdf的程序,最后客户需要生成的同时附带一份记事本文件,就是OCR过后的文本,并指定utf-8格式的。在处理utf-8时出现了点小问题,现在总结如下
首先 利用delphi自带的UTF8Encode函数,将普通字符转换为utf-8编码
创建一个流,MemoryStream或FileStream都可
函数看起来如下
procedure SaveUTF8File(AContent:WideString;AFileName: string);
var
  ffileStream:TFileStream;
  futf8Bytes: string;
  S: string;
begin
  ffileStream:=TFileStream.Create(AFileName,fmCreate);
  futf8Bytes:= UTF8Encode(AContent);
  ffileStream.Write(futf8Bytes[1],Length(futf8Bytes));
  ffileStream.Free;
end;
运行后查看生成的文件,全是乱码,上网搜索发现
unicode文本文件:头两个字符分别是FF   FE(16进制)
utf-8文本文件:头两个字符分别是EF   BB(16进制)
原来是忘了把文件头加进去了
于是加入代码后
procedure SaveUTF8File(AContent:WideString;AFileName: string);
var
  ffileStream:TFileStream;
  futf8Bytes: string;
  S: string;
begin
  ffileStream:=TFileStream.Create(AFileName,fmCreate);
  futf8Bytes:= UTF8Encode(AContent);
  S:=#$EF#$BB#$BF;
  ffileStream.Write(S[1],Length(S));
  ffileStream.Write(futf8Bytes[1],Length(futf8Bytes));
  ffileStream.Free;
end;
保存文件后查看,还是乱码。找了半天问题最后终于发现问题出现在声明的参数WideString上,改成string就没问题了。
最后生成 的代码如下
procedure SaveUTF8File(AContent:string;AFileName: string);
var
  ffileStream:TFileStream;
  futf8Bytes: string;
  S: string;
begin
  ffileStream:=TFileStream.Create(AFileName,fmCreate);
  futf8Bytes:= UTF8Encode(AContent);
  S:=#$EF#$BB#$BF;
  ffileStream.Write(S[1],Length(S));
  ffileStream.Write(futf8Bytes[1],Length(futf8Bytes));
  ffileStream.Free;
end;
再附上一段读取utf-8文本的代码
function  LoadUTF8File(AFileName: string): string;
var
  ffileStream:TFileStream;
  fAnsiBytes: string;
  S: string;
begin
  ffileStream:=TFileStream.Create(AFileName,fmOpenRead);
  SetLength(S,ffileStream.Size);
  ffileStream.Read(S[1],Length(S));
  fAnsiBytes:= UTF8Decode(Copy(S,4,MaxInt));
  Result:= fAnsiBytes;
end;
		