I am working on a personal project that uses a custom configuration file. The main file format is as follows:
[users] name: bob attributes: hat: brown shirt: black another_section: key: value key2: value2 name: sally sex: female attributes: pants: yellow shirt: red
There can be an arbitrary number of users, and each of them can have different key / value pairs, and in the section you can use nested keys / values ββusing tabs. I know that I can use json, yaml or even xml for this configuration file, however I would like to save it to order.
The analysis does not have to be difficult, as I already wrote the code to parse it. My question is what is the best way to parse parsing using clean and structured code, and also write in such a way as not to make difficult changes in the future (there may be many nests in the future). Right now, my code looks completely disgusting. For instance,
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()) { // } } }
As you can see, the code is pretty dirty and I cut it for presentation here. I feel that there are better ways to do this, perhaps not using BufferedReader. Could someone possibly provide a better way or approach that is not as confusing as mine?
source share