How to save classic Delphi string to disk (and read them back)?

前端 未结 4 635
走了就别回头了
走了就别回头了 2021-01-07 16:03

I want to achieve a very very basic task in Delphi: to save a string to disk and load it back. It seems trivial but I had problems doing this TWICE since I upgraded to IOUti

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-07 16:33

    Just use TStringList, until size of file < ~50-100Mb (it depends on CPU speed):

    procedure ReadTextFromFile(const AFileName: string; SL: TStringList);
    begin
      SL.Clear;
      SL.DefaultEncoding:=TEncoding.ANSI; // we know, that old files has this encoding
      SL.LoadFromFile(AFileName, nil); // let TStringList detect real encoding.
      // if not - it just use DefaultEncoding.
    end;
    
    procedure WriteTextToFile(const AFileName: string; const TextToWrite: string);
    var
      SL: TStringList;
    begin
      SL:=TStringList.Create;
      try
        ReadTextFromFile(AFileName, SL); // read all file with encoding detection
        SL.Add(TextToWrite);
        SL.SaveToFile(AFileName, TEncoding.UTF8); // write file with new encoding.
        // DO NOT SET SL.WriteBOM to False!!!
      finally
        SL.Free;
      end;
    end;
    

提交回复
热议问题