用delphi用下面代码
    AssignFile(f1,APath);
    Reset(F1);
    while not Eof(F1) do
    begin
       Readln(F1,Ch);
       Result.Add(Ch);
    end;
    CloseFile(F1);}
读取非ansi格式时,会出现乱码,应该如何解决呢?
我在csdn搜到一篇,用unicode改成ansi读取,可是这种方法显然不行,因为我不知道用户会打开什么格式的文件,总不能要用户自己选吧?我不相信delphi 这个号称"聪明的程序员用的"东东会连这一方面都考虑不到,我想这只是我的水平低的缘故,所以期望csdn的高手指点

解决方案 »

  1.   

    AnsiToUtf8()
    试一下这个函数
      

  2.   

    看错了,
      首先,不同编码的文本,是根据文本的前两个字节来定义其编码格式的。定义如下:  ANSI:        无格式定义;
      Unicode:       前两个字节为FFFE;
      Unicode big endian: 前两字节为FEFF; 
      UTF-8:        前两字节为EFBB;   知道了各种编码格式的区别,写代码就容易了,以下是我在一个软件中写的处理代码:
    (注意,Delphi的TMemo/TRichEdit只支持ANSI的文本文件,其它编码格式的文件需要自行写代码转换成GB2312或BIG5,方能正确显示)type
    TTextFormat=(tfAnsi,tfUnicode,tfUnicodeBigEndian,tfUtf8);
    const
    TextFormatFlag:array[tfAnsi..tfUtf8] of word=($0000,$FFFE,$FEFF,$EFBB); procedure WordLoHiExchange(var w:Word);
    var
    b:Byte;
    begin
      b:=WordRec(w).Lo;
      WordRec(w).Lo:=WordRec(w).Hi;
      WordRec(w).Hi:=b;
    end;{ TextFormat返回文本编码类型,sText未经处理的文本 }
    function ReadTextFile(const FileName: string;
    var TextFormat: TTextFormat; var sText:string);
    var
    w:Word;
    b:Byte;
    begin
      with TFileStream.Create(FileName,fmOpenRead or fmShareDenyNone) do
        try
          Read(w,2);
          WordLoHiExchange(w);//因为是以Word数据类型读取,故高低字节互换
        if w = TextFormatFlag[tfUnicode] then
          TextFormat:= tfUnicode
          else if w = TextFormatFlag[tfUnicodeBigEndian] then
          TextFormat:= tfUnicodeBigEndian
          else if w = TextFormatFlag[tfUtf8] then
          begin
            Read(b,1);//这里要注意一下,UFT-8必须要跳过三个字节。
          TextFormat:=tfUtf8;
          end else
          begin
            TextFormat:=tfANSI;
            Position:=0;
          end;
          SetLength(sText,Size-Position);
          ReadBuffer(sText[1],Size-Position);
          finally
            Free;
          end;
        end; 
    //====================================
    判断出是什么编码后在进行转换就ok吧
      

  3.   

    Utf8ToAnsi()
    UnicodeToUtf8()
    还有这几个函数
      

  4.   

    万分感谢happyggy(Delphi<-&&->java,可是我发现代码在我的电脑上运行有几个问题,我是winxp sp2+d2006
    1.当文本是Unicode时,会识别成 Unicode big endian,反之也是
    2:会把UTF-8识别成ANSI的这是怎么回事呢?高手请指点