tri*_*nth 4 java oop design-patterns configuration-files
我正在开发一个使用自定义配置文件的个人项目.该文件的基本格式如下所示:
[users]
name: bob
attributes:
hat: brown
shirt: black
another_section:
key: value
key2: value2
name: sally
sex: female
attributes:
pants: yellow
shirt: red
Run Code Online (Sandbox Code Playgroud)
可以有任意数量的用户,每个用户可以有不同的键/值对,并且可以使用制表位在一个节下面嵌套键/值.我知道我可以为这个配置文件使用json,yaml甚至xml,但是,我现在想保持自定义.
解析应该不难,因为我已经编写了解析它的代码.我的问题是,使用干净和结构化的代码解析这个问题的最佳方法是什么,以及在未来不会发生变化的方式编写(未来可能会有多个嵌套).现在,我的代码看起来非常恶心.例如,
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()) {
//
}
}
}
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,代码非常混乱,我在这里简化了演示.我觉得有更好的方法可以做到这一点,也许不使用BufferedReader.有人可以提供一种更好的方式或方法,而不是像我的那样复杂吗?