Delphi 如何快速读取非常大的文本文件


本文整理自网络,侵删。

 
代码仅供参考:
代码1
function R(const FileName: string): string;
var
  M: TFileStream;
begin
  M := TFileStream.Create(FileName, fmOpenRead);
  try
    SetLength(Result, M.Size);
    M.Read(Result[1], M.Size);
  finally
    M.Free;
  end;
end;

代码2
function MMFileToString(const AFilename: string): string;
var
  hFile: THandle;
  hFileMap: THandle;
  hiSize: DWORD;
  loSize: DWORD;
  text: string;
  view: pointer;
begin
  Result := '';
  if AFilename = '' then
    Exit;
  if not FileExists(AFilename) then
    Exit;
  {Open the file}
  hFile := CreateFile(
    PChar(AFilename), GENERIC_READ, FILE_SHARE_READ, nil,
    OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0
  );
  if hFile <> INVALID_HANDLE_VALUE then
  begin
    loSize := GetFileSize(hFile, @hiSize);
    {File was opened successfully, now map it:}
    hFileMap := CreateFileMapping(
      hFile, nil, PAGE_READONLY, hiSize, loSize, 'TextForString'
    );
    if (hFileMap <> 0) then
    begin
      if (GetLastError() = ERROR_ALREADY_EXISTS) then
      begin
        MessageDlg(
          'Mapping already exists - not created.', mtWarning, [mbOk], 0
        );
        CloseHandle(hFileMap)
      end
      else
      begin
        try
          {File mapped successfully, now map a view of the file into the
          address space:}
          view := MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, 0);
          if (view <> nil) then
          begin {View mapped successfully}
            {Close file handle - as long is view is open it will persist}
            CloseHandle(hFile);
            SetLength(Result, loSize);
            Move(view^, Result[1], loSize);
          end
          else
            MessageDlg(
              'Unable to map view of file. ' + SysErrorMessage(GetLastError),
              mtWarning, [mbOk], 0
            );
        finally
          UnmapViewOfFile(view);  {Close view}
          CloseHandle(hFileMap);  {Close mapping}
        end
      end
    end
    else
    begin
      MessageDlg(
        'Unable to create file mapping. ' + SysErrorMessage(GetLastError),
        mtWarning, [mbOk], 0
      );
    end;
  end
  else
  begin
    MessageDlg(
      'Unable to open file. ' + SysErrorMessage(GetLastError),
      mtWarning, [mbOk], 0
    );
  end;
end;

相关阅读 >>

Delphi 逐个分解后字符串加载到stringgrid1

Delphi研究之驱动开发篇(六)--利用section与用户模式程

Delphi tnethttpcleint提交json串

Delphi formactivate与formshow事件有什么区别

Delphi 获取北京时间

Delphi 链接文件名合并

Delphi 内存管理[5]

Delphi实现屏幕抓图

Delphi将文件删除至回收站

Delphi中的字符串比较(comparestr)

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...