Delphi 快速读取TXT 指定行的数据

来源:互联网 发布:linux下部署禅道 编辑:程序博客网 时间:2024/06/05 21:08

继上次的问题。在提取了大量的Email 数据后。现在读取数据成了一个问题。今天我取过1~100w的数据。明天我要取100w~200w的数据。在不用数据库的情况下,我搞了一个下午。Delphi Tstringlist 和 textfile 的简单读取是满足不了的。Tstringlist加载不了大数据。普通的textfile 读取指定行,必须循环count到指定行。


想了一下午,然后想到另类点的解决方法。先对齐数据,每行规定一样的长度。比如每行是 255字节。那么100w行就是 255*100w。直接用流seek到相应位置。动手过程中,发现了更加简单的方法。是对齐数据后,配合textfile read实现的。


定义数据结构:

type  TEmail = packed record    Address : string[32];    end;var  MyData : file of TEmail;  Email  : TEmail;

把TXT数据,对齐一下,按照格式生成。

procedure TForm1.btn2Click(Sender: TObject);var  txt:TextFile;  str:string;begin  AssignFile(MyData,'NewSave.txt');  Rewrite(MyData);  AssignFile(txt,'saved.txt');  Reset(txt);  while not Eof(txt) do  begin    str := '';    Readln(txt,str);    Email.Address := str;    write(MyData,Email);  end;  CloseFile(MyData);  CloseFile(txt);  ShowMessage('OK');end;

然后下面是读写的示例:

{ 读取指定行测试 }procedure TForm1.btn1Click(Sender: TObject);var  txt:TextFile;  str:string;begin  AssignFile(MyData,'NewSave.txt');  Reset(MyData);  Seek(MyData,StrToInt(Trim(edt1.Text)));  Read(MyData,Email);  ShowMessage(Email.Address);  CloseFile(MyData);end;

{ 读取1万行测试 }procedure TForm1.btn3Click(Sender: TObject);var  txt:TextFile;  str:string;  i:Integer;begin  AssignFile(MyData,'NewSave.txt');  AssignFile(txt,'10000email.txt');  Rewrite(txt);  Reset(MyData);  Seek(MyData,StrToInt(edt2.Text));  for I := StrToInt(edt2.Text) to StrToInt(edt3.Text) do  begin    Read(MyData,Email);    Writeln(txt,Email.AddRess);  end;  CloseFile(txt);  CloseFile(MyData);  ShowMessage('OK');end;


简单粗暴 快速。

0 0