unit Unit1;

interface

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

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

//分割文件的函数
{参数 1 是要分割的文件名; 参数 2 是要风格文件的大小, 单位是 KB}
{分割后的文件名扩展名用序号替换}
function SplitFile(const FileName: string; Size: Cardinal): Boolean;
var
  fStream: TFileStream;    {原始文件}
  toStream: TMemoryStream; {分文件}
  p,i: Integer;            {p 记录当前指针位置; i 记录这是第几个分的文件}
begin
  Result := False;

  Size := Size * 1024;     {把大小的单位转换为字节}

  fStream := TFileStream.Create(FileName, fmOpenRead);
  p := 0;
  i := 0;

  toStream := TMemoryStream.Create;

  while p < fStream.Size do
  begin
    toStream.Clear;        {清空上次数据}
    fStream.Position := p; {放好指针位置}

    if fStream.Size-p < Size then Size := fStream.Size-p; {最后一个时, 有多少算多少}

    toStream.CopyFrom(fStream, Size); {复制}
    toStream.SaveToFile(FileName + '.' + IntToStr(i));        {保存}
    Inc(i);
    p := p + Size;
  end;

  fStream.Free;
  toStream.Free;
  Result := True;
end;


//合并文件, 参数是其中一个分文件名
function MergeFile(const FileName: string): Boolean;
var
  ms: TMemoryStream; {读取分文件}
  fs: TFileStream;   {合并后的文件}
  path: string;
  i: Integer;
begin
  path := ChangeFileExt(FileName,''); {去掉序号扩展名}
  ShowMessage(path);
  i := 0;

  ms := TMemoryStream.Create;
  fs := TFileStream.Create(path, fmCreate);

  while FileExists(path + '.' + IntToStr(i)) do
  begin
    ms.LoadFromFile(path + '.' + IntToStr(i));
    fs.CopyFrom(ms, 0); {TFileStream 不需要 SetSize; 但如果用 TMemoryStream 就需要}
    Inc(i);
  end;

  ms.Free;
  fs.Free;
end;



//测试分割
procedure TForm1.Button1Click(Sender: TObject);
begin
  SplitFile('c:\temp\test.txt', 10);
end;

//测试合并
procedure TForm1.Button2Click(Sender: TObject);
begin
  MergeFile('c:\temp\test.txt.0');
end;

end.

posted on 2008-01-02 16:31  万一  阅读(8036)  评论(1编辑  收藏  举报