檔案分割/合併是壓縮軟體、安裝包製作、大檔傳輸的基礎功能。Delphi 的 TFileStream 提供高效率的串流讀寫,配合 CopyFrom 方法,幾十行程式碼即可完成。本文詳細說明分割邏輯、擴展名編號規則、合併流程與關鍵細節。
.000, .001 …) 依序讀取分割檔,寫入單一目標檔案。Button1 Caption="分割"Button2 Caption="合併"Edit1 輸入分割塊大小 (位元組)OpenDialog1、SaveDialog1procedure TForm1.Button1Click(Sender: TObject);
var
i, WantedFragSize, RealToWrite: Integer;
InStream, OutStream: TFileStream;
S: String;
begin
if OpenDialog1.Execute then
begin
SaveDialog1.Title := '輸入分割檔基底檔名';
if SaveDialog1.Execute then
begin
WantedFragSize := StrToInt(Edit1.Text);
i := 0;
InStream := TFileStream.Create(OpenDialog1.FileName, fmOpenRead);
try
while InStream.Position < InStream.Size do
begin
// 產生 .000, .001 ... 三位數擴展名
S := IntToStr(i);
while Length(S) < 3 do S := '0' + S;
S := '.' + S;
// 計算實際寫入大小 (最後一塊可能較小)
if InStream.Size - InStream.Position < WantedFragSize then
RealToWrite := InStream.Size - InStream.Position
else
RealToWrite := WantedFragSize;
OutStream := TFileStream.Create(SaveDialog1.FileName + S, fmCreate);
try
OutStream.CopyFrom(InStream, RealToWrite);
Inc(i);
finally
OutStream.Free;
end;
end;
finally
InStream.Free;
end;
ShowMessage('分割完成,共 ' + IntToStr(i) + ' 個檔案。');
end;
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
i: Integer;
InStream, OutStream: TFileStream;
SourcePath, FragName, S: String;
begin
OpenDialog1.Title := '請選擇第一個分割檔 (.000)';
if OpenDialog1.Execute then
begin
SourcePath := ExtractFilePath(OpenDialog1.FileName);
FragName := ExtractFileName(OpenDialog1.FileName);
SaveDialog1.Title := '請輸入合併後的檔名';
if SaveDialog1.Execute then
begin
i := 0;
S := '.000';
FragName := ChangeFileExt(FragName, S);
if FileExists(SourcePath + FragName) then
begin
OutStream := TFileStream.Create(SaveDialog1.FileName, fmCreate);
try
while FileExists(SourcePath + FragName) do
begin
InStream := TFileStream.Create(SourcePath + FragName, fmOpenRead);
try
OutStream.CopyFrom(InStream, 0); // 0 表示全部內容
Inc(i);
S := IntToStr(i);
while Length(S) < 3 do S := '0' + S;
S := '.' + S;
FragName := ChangeFileExt(FragName, S);
finally
InStream.Free;
end;
end;
ShowMessage('合併完成,共處理 ' + IntToStr(i) + ' 個分割檔。');
finally
OutStream.Free;
end;
end
else
ShowMessage('找不到 .000 分割檔,請確認目錄完整性。');
end;
end;
end;
function CopyFrom(Source: TStream; Count: Int64): Int64;
Count = 0:讀取 Source 從目前位置到結尾的所有資料。 0:讀取指定位元組數,並移動 Source 位置指標。分割時用 RealToWrite 精確控制每塊大小;合併時用 0 一次讀完單一分割檔。
InStream.Position / InStream.Size 更新 UI。TThread 避免介面凍結。TFileStream + CopyFrom 是 Delphi 處理大型二進位檔案的利器。掌握串流定位、區塊讀寫、檔案命名規則,即可輕鬆實作分割合併、加密解密、斷點續傳等進階功能。