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

前端 未结 4 638
走了就别回头了
走了就别回头了 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:14

    Code based on David's suggestions:

    {--------------------------------------------------------------------------------------------------
     READ/WRITE UNICODE
    --------------------------------------------------------------------------------------------------}
    
    procedure WriteToFile(CONST FileName: string; CONST aString: String; CONST WriteOp: WriteOperation= woOverwrite; WritePreamble: Boolean= FALSE); { Write Unicode strings to a UTF8 file. It can also write a preamble }
    VAR
       Stream: TFileStream;
       Preamble: TBytes;
       sUTF8: RawByteString;
       aMode: Integer;
    begin
     ForceDirectories(ExtractFilePath(FileName));
    
     if (WriteOp= woAppend) AND FileExists(FileName)
     then aMode := fmOpenReadWrite
     else aMode := fmCreate;
    
     Stream := TFileStream.Create(filename, aMode, fmShareDenyWrite);   { Allow read during our writes }
     TRY
      sUTF8 := Utf8Encode(aString);                                     { UTF16 to UTF8 encoding conversion. It will convert UnicodeString to WideString }
    
      if (aMode = fmCreate) AND WritePreamble then
       begin
        preamble := TEncoding.UTF8.GetPreamble;
        Stream.WriteBuffer( PAnsiChar(preamble)^, Length(preamble));
       end;
    
      if aMode = fmOpenReadWrite
      then Stream.Position:= Stream.Size;                               { Go to the end }
    
      Stream.WriteBuffer( PAnsiChar(sUTF8)^, Length(sUTF8) );
     FINALLY
       FreeAndNil(Stream);
     END;
    end;
    
    
    procedure WriteToFile (CONST FileName: string; CONST aString: AnsiString; CONST WriteOp: WriteOperation);
    begin
     WriteToFile(FileName, String(aString), WriteOp, FALSE);
    end;
    
    
    function ReadFile(CONST FileName: string): String;  {Tries to autodetermine the file type (ANSI, UTF8, UTF16, etc). Works with UNC paths }
    begin
     Result:= System.IOUtils.TFile.ReadAllText(FileName);
    end;
    

提交回复
热议问题