Einzelnen Beitrag anzeigen

Benutzerbild von Sir Rufo
Sir Rufo

Registriert seit: 5. Jan 2005
Ort: Stadthagen
9.454 Beiträge
 
Delphi 10 Seattle Enterprise
 
#2

AW: Stream mit UTF8-Daten dekodieren?

  Alt 20. Okt 2010, 18:34
Delphi-Quellcode:
function StringSaveToFile( const Str, FileName : string;
  const EraseFile : boolean ) : boolean;
  var
    fs : TFileStream;
    Size : integer;
    Buffer, Preamble : TBytes;
    Encoding : TEncoding;
    CreateFile : boolean;
  begin
    Result := False;
    try
      CreateFile := EraseFile or not FileExists( FileName );
      if CreateFile then
        fs := TFileStream.Create( FileName, fmCreate )
      else
        fs := TFileStream.Create( FileName, fmOpenReadWrite );
      try
        if CreateFile then
          begin
            Encoding := TEncoding.default;
            Preamble := Encoding.GetPreamble;
            if Length( Preamble ) > 0 then
              fs.WriteBuffer( Preamble[ 0 ], Length( Preamble ) );
          end
        else
          begin
            Encoding := nil;
            Size := fs.Size - fs.Position;
            if Size > 64 then
              Size := 64;
            SetLength( Buffer, Size );
            TEncoding.GetBufferEncoding( Buffer, Encoding );
            fs.Seek( 0, soFromEnd );
          end;
        Buffer := Encoding.GetBytes( Str );
        fs.WriteBuffer( Buffer[ 0 ], Length( Buffer ) );
      finally
        fs.Free;
      end;

    except
      on E : Exception do
        ;
    end;
  end;

function StringLoadFromFile( const FileName : string ) : string;
  var
    fs : TFileStream;
    Size : integer;
    Buffer : TBytes;
    Encoding : TEncoding;
  begin
    Result := '';
    try

      Encoding := nil;
      if FileExists( FileName ) then
        begin
          fs := TFileStream.Create( FileName, fmOpenRead );
          try

            Size := fs.Size - fs.Position;
            SetLength( Buffer, Size );
            fs.read( Buffer[ 0 ], Size );

            Size := TEncoding.GetBufferEncoding( Buffer, Encoding );
            Result := Encoding.GetString
              ( Buffer, Size, Length( Buffer ) - Size );

          finally
            fs.Free;
          end;
        end;

    except
      on E : Exception do
        ;
    end;
  end;
Kaum macht man's richtig - schon funktioniert's
Zertifikat: Sir Rufo (Fingerprint: ‎ea 0a 4c 14 0d b6 3a a4 c1 c5 b9 dc 90 9d f0 e9 de 13 da 60)
  Mit Zitat antworten Zitat