開(kāi)發(fā)上位機(jī)經(jīng)常會(huì)遇到要保存一些參數(shù)和數(shù)據(jù)到文件挣郭,其中ini迄埃、json、xml是最常用的格式兑障。codetyphon有現(xiàn)成的控件可以侄非,他們是IniPropStorage、JSONPropStorage流译、XMLPropStorage逞怨。通過(guò)簡(jiǎn)單的設(shè)置就可以實(shí)現(xiàn)配置文件的存儲(chǔ)。
IniPropStorage主要屬性:
1.property StoredValues: TStoredValues;
存儲(chǔ)的參數(shù)名和鍵值都在這里添加設(shè)置福澡。
2.property IniFileName: string; Name of the file where the property data is saved in INI format.
要讀取或存儲(chǔ)的ini文件名稱(chēng)叠赦,支持相對(duì)路徑。
3.property IniSection: string; The section on the INI file where values are to be kept.
設(shè)置設(shè)定參數(shù)所在的區(qū)域革砸,理解就是參數(shù)的父節(jié)點(diǎn)名除秀。
4.property Active: Boolean;This determines if the object is active or not.
這個(gè)建議設(shè)置成false,true運(yùn)行發(fā)現(xiàn)有一些問(wèn)題算利,原因不清楚册踩。
image.png
程序設(shè)計(jì)
1.新建application項(xiàng)目,拖拽控件笔时,使界面如下:
2.設(shè)置主要屬性:
Active=false棍好;
IniFileName=config.ini;可以自己手動(dòng)創(chuàng)建該文件,也可以讓程序運(yùn)行時(shí)自動(dòng)創(chuàng)建;
IniSection=Setup借笙;
StoredValues設(shè)置如下圖:
程序代碼
unit main;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls,
IniPropStorage, ExtCtrls, Buttons, kedits;
type
{ TForm1 }
TForm1 = class(TForm)
btnWriteINIFile: TBitBtn;
btnExit: TButton;
btnReadINIFile: TBitBtn;
CheckBox1: TCheckBox;
CheckBox2: TCheckBox;
Edit2: TKNumberEdit;
Edit3: TKNumberEdit;
Edit4: TKNumberEdit;
Edit6: TLabeledEdit;
GroupBox1: TGroupBox;
GroupBox2: TGroupBox;
IniStorage1: TIniPropStorage;
Edit1: TKNumberEdit;
Edit5: TLabeledEdit;
procedure btnExitClick(Sender: TObject);
procedure btnReadINIFileClick(Sender: TObject);
procedure btnWriteINIFileClick(Sender: TObject);
private
public
end;
var
Form1: TForm1;
implementation
{$R *.frm}
{ TForm1 }
procedure TForm1.btnExitClick(Sender: TObject);
begin
Close;
end;
procedure TForm1.btnReadINIFileClick(Sender: TObject);
var
h:String;
begin
h:='';
CheckBox2.Checked:=IniStorage1.ReadBoolean('AutoStart',False);
Edit2.ValueAsInt:=IniStorage1.ReadInteger('Left',0);
Edit4.Value:=IniStorage1.ReadString('Height','0.0').ToDouble;
Edit6.Text:= IniStorage1.ReadString('Name','');
end;
procedure TForm1.btnWriteINIFileClick(Sender: TObject);
begin
IniStorage1.WriteBoolean('AutoStart',CheckBox1.Checked);
IniStorage1.WriteInteger('Left',Edit1.ValueAsInt);
IniStorage1.WriteString('Height',Edit3.ValueAsText);
IniStorage1.WriteString('Name',Edit5.Text);
//IniStorage1.Save;
end;
end.
運(yùn)行效果
JSON和XML文件操作與上面基本一樣扒怖,不在細(xì)述。
···