Delphi Programming

  1. Home
  2. Computing & Technology
  3. Delphi Programming

How to Split and Merge Files

By Zarko Gajic, About.com

There are times when you need to split a large file into several smaller ones (for whatever the purpose is). The following two methods use Delphi TStream objects to break a file into several files with predefined size; and to merge those files back to the original.

~~~~~~~~~~~~~~~~~~~~~~~~~
procedure SplitFile(FileName : TFileName; FilesByteSize : Integer) ;
// FileName == file to split into several smaller files
// FilesByteSize == the size of files in bytes
var
   fs, ss: TFileStream;
   cnt : integer;
   SplitName: String;
begin
   fs := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite) ;
   try
     for cnt := 1 to Trunc(fs.Size / FilesByteSize) + 1 do
     begin
       SplitName := ChangeFileExt(FileName, Format('%s%d', ['._',cnt])) ;
       ss := TFileStream.Create(SplitName, fmCreate or fmShareExclusive) ;
       try
         if fs.Size - fs.Position < FilesByteSize then
           FilesByteSize := fs.Size - fs.Position;
         ss.CopyFrom(fs, FilesByteSize) ;
       finally
         ss.Free;
       end;
     end;
   finally
     fs.Free;
   end;
end;

Note: a 3 KB file 'myfile.ext' will be split into 'myfile._1', 'myfile._2','myfile._3' if FilesByteSize parameter equals 1024 (1 KB).

procedure MergeFiles(FirstSplitFileName, OutFileName : TFileName) ;
// FirstSplitFileName == the name of the first piece of the split file
// OutFileName == the name of the resulting merged file
var
   fs, ss: TFileStream;
   cnt: integer;
begin
   cnt := 1;
   fs := TFileStream.Create(OutFileName, fmCreate or fmShareExclusive) ;
   try
     while FileExists(FirstSplitFileName) do
     begin
       ss := TFileStream.Create(FirstSplitFileName, fmOpenRead or fmShareDenyWrite) ;
       try
         fs.CopyFrom(ss, 0) ;
       finally
         ss.Free;
       end;
       Inc(cnt) ;
       FirstSplitFileName := ChangeFileExt(FirstSplitFileName, Format('%s%d', ['._',cnt])) ;
     end;
   finally
     fs.Free;
   end;
end;

Usage:
SplitFile('c:\mypicture.bmp', 1024) ; //into 1 KB files
...
MergeFiles('c:\mypicture._1','c:\mymergedpicture.bmp') ;
~~~~~~~~~~~~~~~~~~~~~~~~~

Delphi tips navigator:
» How to handle system time change
« Enabling Cassini to use Client-Side Validation in ASP.NET

More Delphi Programming Quick Tips

Explore Delphi Programming

About.com Special Features

Build Your Own Website

Step-by-step advice on how to do everything from choosing a Web host to promoting your content. More >

Connect Your Home Computers

Easy ways to connect two computers for networking purposes. More >

Delphi Programming

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Coding Delphi Applications
  5. Delphi Tips and Tricks
  6. 2005 Delphi Tips
  7. How to Split and Merge Files using Delphi code

©2009 About.com, a part of The New York Times Company.

All rights reserved.