我想从文本文件(数据库名称,用户名,密码)中获取一些值,我找到了一种方法,但不确定是否是最好的方法,导致密码返回某种“制表符空格” “最后,这是正确的方法,还是有另一种方法可以更容易地做到这一点?
这是我的文字档案:
javax.persistence.jdbc.url=jdbc:mysql://address=(protocol=tcp)(host=127.0.0.1)
(port=3306)/A_DBNAME
javax.persistence.jdbc.user=A_USER
javax.persistence.jdbc.password=A_PASSWORD
这是我的代码:
function StrSplit(Text: String; Separator: String): TArrayOfString;
var
i, p: Integer;
Dest: TArrayOfString;
begin
i := 0;
repeat
SetArrayLength(Dest, i+1);
p := Pos(Separator,Text);
if p > 0 then begin
Dest[i] := Copy(Text, 1, p-1);
Text := Copy(Text, p + Length(Separator), Length(Text));
i := i + 1;
end else begin
Dest[i] := Text;
Text := '';
end;
until Length(Text)=0;
Result := Dest
end;
procedure InitializeWizard;
var
file : AnsiString;
dbName, pass, user : TArrayOfString;
begin
LoadStringFromFile( ExpandConstant('{src}\jdbcfile.txt'), file);
user := StrSplit(file, 'javax.persistence.jdbc.user=');
user := StrSplit(user[1],'javax.persistence.jdbc.password=')
MsgBox('User: '+user[0],mbInformation,MB_OK);
pass := StrSplit(file,'javax.persistence.jdbc.password=');
MsgBox('Pass: '+pass[1],mbInformation,MB_OK);
dbName := StrSplit(file, ')/');
dbName := StrSplit(dbName[1],'javax.persistence.jdbc.user=');
MsgBox('dbName: '+dbName[0],mbInformation,MB_OK);
end;
答案 0 :(得分:1)
key=value
)和单个键值(.url
)在概念上是错误的。此外,您依赖于文件中的特定键顺序,这也是错误的。
.url
键具有类似路径的结构,因此您可以“滥用”ExtractFileName
function。function GetKeyValue(Lines: TStrings; Key: string): string;
var
I, P: Integer;
begin
for I := 0 to Lines.Count - 1 do
begin
P := Pos('=', Lines[I]);
if (P > 0) and (CompareText(Trim(Copy(Lines[I], 1, P - 1)), Key) = 0) then
begin
Result := Trim(Copy(Lines[I], P + 1, Length(Lines[I]) - P));
Exit;
end;
end;
{ Implicitly returns an empty string, if the key does not exist. }
{ Alternatively you can also throw an exception by using RaiseException function, }
{ or return some default value [by adding an additional parameter to this function]. }
end;
procedure InitializeWizard;
var
Lines: TStringList;
DbName, User, Password: string;
begin
Lines := TStringList.Create;
Lines.LoadFromFile(ExpandConstant('{src}\jdbcfile.txt'));
DbName := ExtractFileName(GetKeyValue(Lines, 'javax.persistence.jdbc.url'));
User := GetKeyValue(Lines, 'javax.persistence.jdbc.user');
Password := GetKeyValue(Lines, 'javax.persistence.jdbc.password');
Lines.Free;
{ ... }
end;