關於 Delphi 中流的使用(9) 分割與合併檔案的函式
阿新 • • 發佈:2019-02-04
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; varForm1: 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 thenSize := 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.