Delphi实现读写文本文件

Delphi
placeholder image
admin 发布于:2017-11-17 15:38:47
阅读:loading

基本介绍

本示例主要为Delphi实现的读、写文本文件和读取ini文件,实现较为简单,给出源码和运行效果图,当初不曾知道我有一天也会用到Pascal语言,前台显示的语法着色也没有加上这的支持,分别给出截图和文本版,代码实现分别为:

(1)、点击【写文件】按钮,程序将在相应目录下创建txt文件,并向其中写入内容,路径为:d:\test\test.txt,多次点击将写入多次内容,每次写入内容会追加一个新行;

(2)、点击【读文件】按钮,程序同样将读取该文件,将读取到的文件以弹出框的形式展示其内容;

(3)、点击【读取ini文件】按钮,程序将读取c:\Windows\win.ini文件中的MAIL类型中的一个参数;

参考代码

image.png

参考代码

unit FileWindowTest;

 

interface

 

uses

  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

  Dialogs, StdCtrls , IniFiles;

 

type

  TFileWindow = class(TForm)

    writeButton: TButton;

    readButton: TButton;

    readIniButton: TButton;

    procedure writeButtonClick(Sender: TObject);

    procedure readButtonClick(Sender: TObject);

    procedure readIniButtonClick(Sender: TObject);

  private

    { Private declarations }

  public

    { Public declarations }

  end;

 

var

  FileWindow: TFileWindow;

 

implementation

 

{$R *.dfm}

 

//按行写文件

procedure TFileWindow.writeButtonClick(Sender: TObject);

var

    fileFolder : String;

    filePath : String;

    txtFile : TextFile;

    rowContent : String;

begin

    fileFolder := 'd:\test';

    filePath := fileFolder + '\test.txt';

    //-----------------------------------

    if DirectoryExists(fileFolder) = false then //文件夹是否存在

    begin

        CreateDir(fileFolder);

    end;

    AssignFile(txtFile , filePath);

    if FileExists(filePath) = false then  //判断文件是否存在

    begin

        ReWrite(txtFile);//创建并打开一个新文件

    end;

    Append(txtFile);//文件内容追加

    Randomize;//改变随机种子

    rowContent := 'hello,中文,' + inttostr(Random(10000));

    showmessage('写入的内容为:' + rowContent);

    Writeln(txtFile , rowContent);//写入一行数据

    CloseFile(txtFile);//释放文件

 

end;

 

//按行读取文件

procedure TFileWindow.readButtonClick(Sender: TObject);

var

    filePath : String;

    txtFile : TextFile;

    totalContent : String;

    rowContent : String;//一行内容

begin

     filePath := 'd:\test\test.txt';

     AssignFile(txtFile , filePath);

     Reset(txtFile);//只读打开

     while not Eof(txtFile) do

     begin

         Readln(txtFile , rowContent);

         totalContent := totalContent + rowContent + char(13) + char(10); //每行数据后添加一个回车换行

     end;

     CloseFile(txtFile);

     showmessage(totalContent);

 

end;

 

//读取ini文件,系统自带的

procedure TFileWindow.readIniButtonClick(Sender: TObject);

var

    iniFile:TiniFile;

    value : string;

begin

    iniFile := TiniFile.Create('C:\Windows\win.ini');//读取配置文件

    //打开这个ini文件可以看出Mail[Mail]组里面的MAPIXVER参数

    value := iniFile.ReadString('Mail' , 'MAPIXVER' , '');

    iniFile.Free;//释放对象

 

    showmessage('读取的参数值为:' + value);

 

end;

 

end.

运行效果

读写文件示例.gif

上述许多内容已经过时和过期了,留存本篇文章仅为方便个人查看,原始文章的信息参考:

原始链接:https://www.chendd.cn/information/viewInformation/other/208.a

最后更新:2017-11-17 15:38:47

访问次数:578

评论次数:0

点赞个数:0

 点赞


 发表评论

当前回复:作者

 评论列表


留言区