procedure TForm1.Button1Click(Sender: TObject);
const
GetPath = 'E:\Software\DevExpressVCL.v54.rar';
SetPath = 'E:\Software\D.rar';
var
GetStream, SetStream: TStream;
intNum, int: Integer;
buffer: PByte;
intBufferSize, intBlock: Integer;
begin
if not FileExists(GetPath) then
begin
ShowMessage('源文件不存在!');
Exit;
end; {打开源文件}
GetStream := TFileStream.Create(GetPath, fmOpenRead or fmShareExclusive);
SetStream := TFileStream.Create(SetPath, fmCreate);
intNum := GetStream.Size; //源文件大小
SetStream.Size := intNum; //赋给目标文件
GetStream.Position := 0; {流指针移到开始, 复制时从这里开始}
SetStream.Position := 0;
intBufferSize := intNum;
intBlock := intBufferSize div 100;
GetMem(buffer, intBufferSize); //给buffer分配空间
while intNum <> 0 do begin
Application.ProcessMessages; //避免假死
int := intBlock;
if int > intNum then
int := intNum;
GetStream.ReadBuffer(buffer^, int);
SetStream.WriteBuffer(buffer^, int);
ProgressBar1.Position := Trunc((1 - intNum / intBufferSize) * 100);
Dec(intNum, int); //传了多少,减多少
end;
...//(后面省略)
为了更好的理解while循环,求详细解释。特别是ReadBuffer那儿,不怎么理解。30分,够吧?
const
MaxBufSize = $F000;
var
BufSize, N: Integer;
Buffer: PChar;
begin
if Count = 0 then
begin
Source.Position := 0;
Count := Source.Size;
end;
Result := Count;
if Count > MaxBufSize then BufSize := MaxBufSize else BufSize := Count;
GetMem(Buffer, BufSize);
try
while Count <> 0 do
begin
if Count > BufSize then N := BufSize else N := Count;
Source.ReadBuffer(Buffer^, N);
WriteBuffer(Buffer^, N);
Dec(Count, N);
end;
finally
FreeMem(Buffer, BufSize);
end;
end;这是TStream 的源码