FileStream類幾乎可以處理所有的文件操作.
以下為一個日志類,除了配置不太靈活外,挺好用的.
type
TBuffer = array [0..2000] of char;
TGameLogFile = class
private
FFullPath:string;//完整路徑,用這個路徑來判斷當前的打開的日志的大小.
FileDate:TDateTime;
FFileParth: string; //路徑
FText: Text;
FLogFileStream:TFileStream;
FIsCreateToNew: boolean; //是否是每次啟動程序都創建新的記錄文件 否則就是當天只會有1個文件
FIsControlFileSize:Boolean;//是否控制文件大小,true,超出文件大小時,重新創建一個log文件
public
{帶入日志文件存放的目錄位置}
constructor Create(Iparth: string);
destructor Destroy; override;
{寫入內容即可自動記錄}
procedure init(Iparth: string);
procedure AddLog(Icon: string; const LogLevel: Integer = 0);
property IsCreateToNew: boolean read FIsCreateToNew write FIsCreateToNew;
end;
implementation
uses StdCtrls;
const
{分割符號}
CSplitStr = '===============================================================';
ClogFileName = '.log';
{ TGameLogFile }
procedure TGameLogFile.AddLog(Icon: string; const LogLevel: integer = 0);
var
txt:string;
buffer:TBuffer; //開一個2K的緩存
begin
try
if FIsCreateToNew then
if Date - FileDate >= 1 then //超過一天.強制換掉日志文件
begin
CloseFile(FText);
init(FFileParth);
end;
if FIsControlFileSize then
begin
if FLogFileStream.Size > 3 * 1000 * 1000 then //這里的單位是M,有時間改成可配置
init(FFileParth); //重新切換一個日志
end;
StrCopy(buffer,PChar(Icon));
FLogFileStream.Write(buffer,Length(Icon));//如果直接write(Icon,Length(Icon)),會產生亂碼.
except
IOResult;
end;
end;
constructor TGameLogFile.Create(Iparth: string);
begin
FIsCreateToNew := false;
FIsControlFileSize := not (FIsCreateToNew xor False); //當FIsCreateToNew為true時,此變量為假
FFileParth := Iparth;
init(FFileParth);
end;
//在這里創建一個日志文件
procedure TGameLogFile.init(Iparth: string);
var
Ltep: string;
begin
if not DirectoryExists(FFileParth) then
if not CreateDir(FFileParth) then begin
raise Exception.Create('錯誤的路徑,日志類對象不能被創建');
exit;
end;
if FIsCreateToNew then begin
Ltep := FormatDateTime('yyyymmddhhnnss', Now);
FileClose(FileCreate(FFileParth + ltep + ClogFileName));
end
else
Ltep := FormatDateTime('yyyymmddhhnnss', Now);
if not FileExists(FFileParth + ltep + ClogFileName) then
FileClose(FileCreate(FFileParth + ltep + ClogFileName));
FileDate := Date;
FFullPath := FFileParth + ltep + ClogFileName;
//此處改用TFileStream用來控制Log日志文件的大小 2011年8月24日9:28:25 ddz
//AssignFile(FText, FFileParth + ltep + ClogFileName);
if Assigned(FLogFileStream) then
FLogFileStream.Free;
//新建日志文件.
FLogFileStream := TFileStream.Create(FFullPath,fmCreate or fmShareDenyNone);
FLogFileStream.free;
//讀寫日志文件
FLogFileStream := TFileStream.Create(FFullPath,fmOpenReadWrite or fmShareDenyNone);
end;
destructor TGameLogFile.Destroy;
begin
try
if Assigned(FLogFileStream) then
FreeAndNil(FLogFileStream);
except
end;
inherited;
end;
end.