我想从文本文件中获取一些值(数据库名称、用户名、密码),我找到了一种方法来做到这一点,但不确定是否是最好的方法,导致密码返回时带有某种“制表符空格”最后,这是正确的方法还是有其他更简单的方法?
这是我的文本文件:
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;
Imo,尝试同时解析整个文件结构(
key=value
)和单个键值(.url
)在概念上是错误的。而且你依赖于文件中的特定键顺序,这也是错误的。
.url
键具有类似路径的结构,因此您可以“滥用”ExtractFileName
功能。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;