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

http://blog.csdn.net/MichaelJScofield/article/details/41869785

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

 

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

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

定义数据结构:

[delphi] view plain copy
 
  1. type  
  2.   TEmail = packed record  
  3.     Address : string[32];  
  4.     end;  
  5.   
  6. var  
  7.   MyData : file of TEmail;  
  8.   Email  : TEmail;  

把TXT数据,对齐一下,按照格式生成。
[delphi] view plain copy
 
  1. procedure TForm1.btn2Click(Sender: TObject);  
  2. var  
  3.   txt:TextFile;  
  4.   str:string;  
  5. begin  
  6.   AssignFile(MyData,'NewSave.txt');  
  7.   Rewrite(MyData);  
  8.   AssignFile(txt,'saved.txt');  
  9.   Reset(txt);  
  10.   while not Eof(txt) do  
  11.   begin  
  12.     str := '';  
  13.     Readln(txt,str);  
  14.     Email.Address := str;  
  15.     write(MyData,Email);  
  16.   end;  
  17.   CloseFile(MyData);  
  18.   CloseFile(txt);  
  19.   ShowMessage('OK');  
  20. end;  

然后下面是读写的示例:
[delphi] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. { 读取指定行测试 }  
  2. procedure TForm1.btn1Click(Sender: TObject);  
  3. var  
  4.   txt:TextFile;  
  5.   str:string;  
  6. begin  
  7.   AssignFile(MyData,'NewSave.txt');  
  8.   Reset(MyData);  
  9.   Seek(MyData,StrToInt(Trim(edt1.Text)));  
  10.   Read(MyData,Email);  
  11.   ShowMessage(Email.Address);  
  12.   CloseFile(MyData);  
  13. end;  

[delphi] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. { 读取1万行测试 }  
  2. procedure TForm1.btn3Click(Sender: TObject);  
  3. var  
  4.   txt:TextFile;  
  5.   str:string;  
  6.   i:Integer;  
  7. begin  
  8.   AssignFile(MyData,'NewSave.txt');  
  9.   AssignFile(txt,'10000email.txt');  
  10.   Rewrite(txt);  
  11.   Reset(MyData);  
  12.   Seek(MyData,StrToInt(edt2.Text));  
  13.   for I := StrToInt(edt2.Text) to StrToInt(edt3.Text) do  
  14.   begin  
  15.     Read(MyData,Email);  
  16.     Writeln(txt,Email.AddRess);  
  17.   end;  
  18.   CloseFile(txt);  
  19.   CloseFile(MyData);  
  20.   ShowMessage('OK');  
  21. end;  
delphi lazarus opengl 网页操作自动化, 图像分析破解,游戏开发
原文地址:https://www.cnblogs.com/delphi-xe5/p/6368222.html