delphi2007 读取得unicode文本显示出来时乱码?
 我换成 anis显示出来就对了我用了 
var
txt:TextFile;
ws:WideString;
str:string;
begin
assignFile(txt,'1.txt');
reset(txt);
read(txt,ws);
memo1.Lines.Text:=string(ws);
closeFile(txt);读出来还是错的 不修改程序 把1.txt转换成anis就对了 高手指教 如何读取 unicode文件

解决方案 »

  1.   

    正好今天在編程序,把我寫的讀寫unicode及utf-8的函數上傳到這裡。
    // 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;
      

  2.   

    utf8Head:   Array[0..2] of Char = (#239,#$bb,#$bf);
    unicodeHead: Array[0..1] of Char = (#255,#$fe);剛才的程序代碼忘了常量的定義了,需要上面這2行的常量。