Delphi知识中心
www.delphi.ee
提供Delphi技术知识
与Delphi程序员共同进步


在线服务QQ:99923144 随时恭候您的光临
首页 基础知识 WIN系统 组件使用 组件开发 数据库 ACTIVEX 多媒体技术 网络技术 关于
文章类别:基础知识    你尚未登陆,会员功能无法使用,请从 网站首页 登陆。
  Delphi分割文本文件源码  
 
Delphi分割文本文件源码

万一老师您好,经常来您博客学习,今天碰到一个问题,如何把一个txt文件按指定大小分割成若干个txt文件啊?
比如说一个txt格式的小说 大小有2M,放到手机里看很不方便,我想把它按100个字节分成若干个应该怎样做?谢谢

代码:

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;

type
TForm1 = class(TForm)
Edit1: TEdit;
Button1: TButton;
OpenDialog1: TOpenDialog;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
begin
Edit1.Text := '10'; //10 KB
Edit1.NumbersOnly := True;
OpenDialog1.Filter := 'TEXT|*.txt|*.*|*.*';
end;

procedure TForm1.Button1Click(Sender: TObject);
var
fs: TFileStream;
ms: TMemoryStream;
path: string;
size,sizeEnd,count,i: Integer;
c: Char;
begin
if OpenDialog1.Execute then path := OpenDialog1.FileName;
if not FileExists(path) then Exit;

fs := TFileStream.Create(path, fmOpenRead);
fs.Read(c, 1);
if CharInSet(c, [#$EF, #$FE, #$FF]) then
begin
ShowMessage('只适用于 ANSI 格式的文本文件');
fs.Free;
Exit;
end;

TButton(Sender).Enabled := False;
size := StrToIntDef(Edit1.Text, 10) * 1024;
count := fs.Size div size;
sizeEnd := fs.Size mod size;
if sizeEnd > 0 then Inc(count);

ms := TMemoryStream.Create;
fs.Position := 0;
for i := 0 to count - 1 do
begin
Text := Format('%d/%d', [i+1, count]);
Application.ProcessMessages;
if (i = count - 1) then size := sizeEnd;
ms.Size := size;
fs.Read(ms.Memory^, size);
ms.SaveToFile(Format('%s_%.3d.txt', [ChangeFileExt(path, ''), i+1]));
fs.Position := size * (i+1);
end;
fs.Free;
ms.Free;
TButton(Sender).Enabled := True;
Text := '完成';
end;

end.


窗体:

object Form1: TForm1
Left = 0
Top = 0
Caption = 'Form1'
ClientHeight = 122
ClientWidth = 231
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
OnCreate = FormCreate
PixelsPerInch = 96
TextHeight = 13
object Edit1: TEdit
Left = 80
Top = 24
Width = 75
Height = 21
TabOrder = 0
Text = 'Edit1'
end
object Button1: TButton
Left = 80
Top = 62
Width = 75
Height = 25
Caption = 'Button1'
TabOrder = 1
OnClick = Button1Click
end
object OpenDialog1: TOpenDialog
Left = 24
Top = 40
end
end


 

在线服务QQ:99923144 Delphi程序员QQ群(139442)
Delphi知识中心 www.delphi.ee 最专业的Delphi技术资料网站