我正在处理一个使用自定义配置文件的个人项目。文件的基本格式如下所示:
[users]
name: bob
attributes:
hat: brown
shirt: black
another_section:
key: value
key2: value2
name: sally
sex: female
attributes:
pants: yellow
shirt: red
可以有任意数量的用户,每个用户可以有不同的键/值对,并且可以使用制表位在一个部分下嵌套键/值。我知道我可以为这个配置文件使用 json、yaml 甚至 xml,但是,我现在想保持自定义。
解析应该一点也不难,因为我已经编写了代码来解析它。我的问题是,使用clean 和structured 代码来解析它的最佳方法是什么? (以后可能会有多个巢穴)。现在,我的代码看起来非常恶心。例如,
private void parseDocument() {
String current;
while((current = reader.readLine()) != null) {
if(current.equals("") || current.startsWith("#")) {
continue; //comment
}
else if(current.startsWith("[users]")) {
parseUsers();
}
else if(current.startsWith("[backgrounds]")) {
parseBackgrounds();
}
}
}
private void parseUsers() {
String current;
while((current = reader.readLine()) != null) {
if(current.startsWith("attributes:")) {
while((current = reader.readLine()) != null) {
if(current.startsWith("\t")) {
//add user key/values to User object
}
else if(current.startsWith("another_section:")) {
while((current = reader.readLine()) != null) {
if(current.startsWith("\t")) {
//add user key/values to new User object
}
else if (current.equals("")) {
//newline means that a new user is up to parse next
}
}
}
}
}
else if(!current.isEmpty()) {
//
}
}
}
如您所见,代码非常困惑,我已将其缩短以便于此处进行演示。我觉得有更好的方法可以做到这一点,也许不使用 BufferedReader。有人可以提供一种不像我的那样复杂的更好的方法或方法吗?
最佳答案
我建议不要为配置文件创建自定义代码。您提出的建议与 YAML 相去不远。 (getting started)。改用它。
关于java - 解析此配置文件的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3498426/