计算机二级Delphi辅导:文件/流的加密解密方法
来源:优易学  2011-6-5 16:59:22   【优易学:中国教育考试门户网】   资料下载   IT书店

  unit uCompress;
  interface
  uses
  Windows, Messages, SysUtils, Variants, Classes, ComCtrls, Dialogs;
  // 压缩/解压文件
  procedure CompressFile(Source, Target: String); stdcall;
  procedure DecompressFile(Source, Target: String); stdcall;
  // 压缩/解压文件到流
  procedure CompressToStream(FileName: String; Stream: TStream); stdcall;
  procedure DecompressToStream(FileName: String; Stream: TStream); stdcall;
  // 压缩/解压流
  procedure CompressStream(InStream, OutStream: TStream); stdcall;
  procedure DecompressStream(InStream, OutStream: TStream); stdcall;
  implementation
  uses
  ZLib;
  const
  COMPRESS_ERROR = ’压缩文件时出现内部错误:’;
  DECOMPRESS_ERROR = ’解压文件时出现内部错误:’;
  COMPRESS_STRM_ERROR = ’压缩流时出现内部错误:’;
  DECOMPRESS_STRM_ERROR = ’解压流时出现内部错误:’;
  BufSize = $4096;  
  // 压缩文件
  procedure CompressFile(Source, Target: String);
  var
  i: Integer;
  Buf: array[0..BufSize] of byte;
  ComStream: TCompressionStream;
  InStream, OutStream: TFileStream;
  begin
  if not FileExists(Source) then
  Exit;
  InStream := Nil;
  OutStream := nil;
  ComStream := nil;
  try
  // 生成流
  InStream := TFileStream.Create(Source, fmOpenRead OR fmShareDenyNone);
  OutStream := TFileStream.Create(Target, fmCreate OR fmShareDenyWrite);
  ComStream := TCompressionStream.Create(clMax, OutStream);
  // 压缩流
  for i := 1 to (InStream.Size div BufSize) do begin
  InStream.ReadBuffer(Buf, BufSize);
  ComStream.Write(Buf, BufSize);
  end;
  i := InStream.Size mod BufSize;
  if (i > 0) then begin
  InStream.ReadBuffer(Buf, i);
  ComStream.Write(Buf, i);
  End;
  InStream.Free;
  InStream := nil;
  // 注先后
  ComStream.Free;
  ComStream := nil;
  // 在此写加密流代码(要先释放 ComStream)
  // EncryptStream(OutStream);
  OutStream.Free;
  OutStream := nil;
  except
  on E: Exception do begin
  if (InStream <> nil) then
  InStream.Free;
  if (OutStream <> nil) then
  OutStream.Free;
  if (ComStream <> nil) then
  ComStream.Free;
  MessageDlg(COMPRESS_ERROR + #10 + E.Message, mtError, [mbOk], 0);
  end;
  end;
  end;

[1] [2] [3] [4] 下一页

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训