//资料来源 :一个把字符转换成各种编码文件的delphi2010函数. - textbox - IT博客 http://www.cnitblog.com/textbox/archive/2011/03/03/72913.aspx
1 procedure SaveFile(const FileName:string; Source: string ; 2 encoding:TEncoding); 3 var 4 sl: TStrings; 5 memoStream: TFileStream; 6 buff: Tbytes; 7 LByteOrderMark: TBytes; 8 begin 9 if Source='' then 10 exit ; 11 try 12 buff:=encoding.GetBytes(Source); 13 memoStream:= TFileStream.Create(FileName, fmCreate); 14 LByteOrderMark:=encoding.GetPreamble; 15 memoStream.Write(LByteOrderMark[ 0 ], Length(LByteOrderMark)); 16 memoStream.Write(buff[ 0 ], length(buff)); 17 finally 18 memoStream.Free; 19 end ; 20 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 繁体