Delphi中把字符串存储成各种编码的txt文档

procedure SaveFile(const FileName:string; Source: string ;
   encoding:TEncoding);
var
  sl: TStrings;
  memoStream: TFileStream;
  buff: Tbytes;
  LByteOrderMark: TBytes;
begin
  if Source='' then
      exit ;
  try
    buff:=encoding.GetBytes(Source);
    memoStream:= TFileStream.Create(FileName, fmCreate);
    LByteOrderMark:=encoding.GetPreamble;
    memoStream.Write(LByteOrderMark[ 0 ], Length(LByteOrderMark));
    memoStream.Write(buff[ 0 ], length(buff));
  finally
    memoStream.Free;
  end ;
end ;

 

SaveFile('C:\Temp\test_' + 'ascii_gbk.txt', ss, TEncoding.GetEncoding(936));//gbk
SaveFile('C:\Temp\test_' + 'ascii_bg5.txt', ss, TEncoding.GetEncoding(950));//bg5 繁体
SaveFile('C:\Temp\test_' + 'utf8.txt', ss, TEncoding.UTF8);
SaveFile('C:\Temp\test_' + 'unicode.txt', ss, TEncoding.Unicode);
unicode转中文的时候必须要制定页码,不然会出现乱码.比如的以下这两句.
SaveFile('C:\Temp\test_' + 'ascii_gbk.txt', ss, TEncoding.GetEncoding(936));//gbk
SaveFile('C:\Temp\test_' + 'ascii_bg5.txt', ss, TEncoding.GetEncoding(950));//bg5 繁体

 

THE END