本例效果图:



代码文件:
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Memo1: TMemo;
    Memo2: TMemo;
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

{读文件为十六进制字符的函数}
function ReadFileToHex(FileName: string): string;
var
  bs: TBytesStream;
  i: Integer;
begin
  Result := '';
  if not FileExists(FileName) then Exit;

  bs := TBytesStream.Create;
  bs.LoadFromFile(FileName);
  for i := 0 to bs.Size - 1 do
    Result := Result + Format('%.2x ', [bs.Bytes[i]]);
  bs.Free;
end;

{测试}
procedure TForm1.Button1Click(Sender: TObject);
const
  FilePath = 'c:\temp\Text.txt';
begin
  Memo1.Lines.SaveToFile(FilePath);
  Memo2.Text := ReadFileToHex(FilePath);
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  Button1.Caption := '保存并读出十六进制 (注意读出的 0D 0A 是换行符)';
end;

end.

窗体文件:
object Form1: TForm1
  Left = 0
  Top = 0
  Caption = 'Form1'
  ClientHeight = 149
  ClientWidth = 339
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  OnCreate = FormCreate
  PixelsPerInch = 96
  TextHeight = 13
  object Memo1: TMemo
    Left = 0
    Top = 0
    Width = 160
    Height = 124
    Align = alLeft
    Lines.Strings = (
      'Memo1')
    ScrollBars = ssVertical
    TabOrder = 0
  end
  object Memo2: TMemo
    Left = 179
    Top = 0
    Width = 160
    Height = 124
    Align = alRight
    Lines.Strings = (
      'Memo2')
    ScrollBars = ssVertical
    TabOrder = 1
  end
  object Button1: TButton
    Left = 0
    Top = 124
    Width = 339
    Height = 25
    Align = alBottom
    Caption = 'Button1'
    TabOrder = 2
    OnClick = Button1Click
  end
end

posted on 2008-09-04 17:28  万一  阅读(6682)  评论(9编辑  收藏  举报