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.