Delphi中文件拷贝方法集合

来源:互联网 发布:西安儿童医院网络预约 编辑:程序博客网 时间:2024/05/29 16:49

一、使用文件流的方法进行拷贝,当然。同样的道理,你也可以使用内存流等方法进行文件的拷贝,原理是一样的。

procedure copyfile(sourcefilename,targetfilename : String);
var f1, f2: tfilestream;
begin
 f1 := tfilestream.Create(sourcefilename, fmopenread);
 try
   f2 := tfilestream.Create(targetfilename, fmopenwrite or fmcreate);
   try
     f2.CopyFrom(f1, f1.Size);
   finally
     f2.Free;
   end;
 finally
   f1.Free;
 end;
end;

二、使用BLOCKREAD和BLOACKWRITE的方法进行文件的拷贝。

Procedure FileCopy(const Fromfile, Tofile: string);
var
 F1, F2: file;
 NumRead, Numwritten: integer;
 Buf: array[1..2048] of char;
begin
 AssignFile(F1, Fromfile);
 reset(F1, 1);
 AssignFile(F2, Tofile);
 Rewrite(F2, 1);
 repeat
   BlockRead(F1, Buf, sizeof(Buf), NumRead);
   BlockWrite(F2, Buf, NumRead, Numwritten);
 until (NumRead = 0) or (Numwritten <> NumRead);
 closefile(F1);
 closefile(F2);
end;

三、使用API文件进行文件的复制
procedure CopyFile(FromFileName, ToFileName: string);
var
 f1, f2: file;
begin
 AssignFile(f1, FromFileName);
 AssignFile(f2, ToFileName);
 reset(f1);
 try
   Rewrite(f2);
   try
     if Lzcopy(TfileRec(f1).handle, TfileRec(f2).handle) < 0
       then
       raise EinoutError.Create('文件复制错误');
   finally
     closefile(f1);
   end;
 finally
   closefile(f2);
 end;
end;

四、Windows API函数 实现文件的拷贝

function CopyFile(lpExistingFileName, lpNewFileName: PChar; bFailIfExists: BOOL): BOOL; stdcall;


参数说明:
lpExistingFileName    :    原文件名称;
lpNewFileName        :  目标文件名称
bFailIfExists              :  如果文件存在,是否覆盖原文件,True表示覆盖;False表示不覆盖。默认为True;

使用示例:
CopyFile(PChar(Edit1.text),PChar(Edit2.text),true);

五、使用API函数实现文件的转移。
API原型:function MoveFile(lpExistingFileName, lpNewFileName: PChar): BOOL; stdcall;

参数:
lpExistingFileName
必选项。要移动的文件的路径。source 参数字符串仅可在路径的最后一个组成部分中用通配符。

lpNewFileName
必选项。指定路径,表示要将文件移动到该目标位置。destination 参数不能包含通配符。

说明
如 果 source 包含通配符或 destination 以路径分隔符 (/) 结束,则假定 destination 指定现有文件夹,将匹配文件移动到该文件夹中。否则,假定 destination 是要创建的目标文件。在任一种情况下,移动单个文件时,可能出现以下三种情况:

如果 destination 不存在,则进行文件移动。这是通常会发生的情况。
如果 destination 是已经存在的文件,则会出现错误。
如果 destination 是目录,则会出现错误。
如果在 source 使用通配符,但没有匹配文件时,也会出现错误。MoveFile 方法在遇到出现的第一个错误时停止。该方法不会撤消错误发生前所作的任何更改。

原创粉丝点击