I have been playing with Java for around a year and I started writing this API for storing data in files. I wrote this method which will save the parameters in a "key: value" format in a file.
The method is getting fairly long and I am just wondering if there is a better/shorter/more efficient way to do this.
public void set(String key, Object value) {
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(this.path, true));
BufferedReader br = new BufferedReader(new FileReader(this.path));
ArrayList<String> file = new ArrayList<String>();
if(this.getValue(key) != null) {
for(String line; (line = br.readLine()) != null;) {
if(line.startsWith(this.COMMENT_PREFIX)) {
file.add(line);
} else if(line.isEmpty()) {
file.add("");
} else {
try {
if(!line.contains(":")) {
throw new MyFormatException("Missing a colon!");
}
} catch(MyFormatException e) {
e.printStackTrace();
bw.close();
br.close();
return;
}
String lineKey = line.substring(0, line.indexOf(":"));
String lineValue = line.substring(line.indexOf(":") + 2);
if(lineKey.equals(key)) {
if(value instanceof ArrayList) {
StringBuilder newValue = new StringBuilder(value.toString());
newValue.replace(value.toString().lastIndexOf("]"), value.toString().lastIndexOf("]") + 1, "");
newValue.replace(value.toString().indexOf("["), value.toString().indexOf("[") + 1, "");
bw.append(key + ": " + newValue.toString());
bw.newLine();
} else {
file.add(lineKey + ": " + value);
}
} else {
file.add(lineKey + ": " + lineValue);
}
}
}
this.clear();
for(String line : file) {
bw.append(line);
bw.newLine();
}
} else {
if(value instanceof ArrayList) {
StringBuilder newValue = new StringBuilder(value.toString());
newValue.replace(value.toString().lastIndexOf("]"), value.toString().lastIndexOf("]") + 1, "");
newValue.replace(value.toString().indexOf("["), value.toString().indexOf("[") + 1, "");
bw.append(key + ": " + newValue.toString());
bw.newLine();
} else {
bw.append(key + ": " + value);
bw.newLine();
}
}
br.close();
bw.close();
} catch(Exception e) {
e.printStackTrace();
}
}