I have this method that reads a file into a hashmap. I feel like there are too many levels in this code with all these tries, ifs and so on. How do you think this can be improved?
public static ExchangeHistory loadHistory(String path){
Map<Integer, Date> rtcHistory = new HashMap<Integer, Date>();
Map<Integer, Date> almHistory = new HashMap<Integer, Date>();
ExchangeHistory exchHist = new ExchangeHistory(rtcHistory, almHistory);
File file = new File(path);
BufferedReader reader = null;
try{
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line;
int lineNumber = 1;
// read file line by line
while ((line = reader.readLine()) != null){
String[] tokens = line.split("\\s");
if (tokens.length != 3){
log.error("Unable to parse exchange history file at line: " + lineNumber);
continue;
}
// try to parse line. if parsing fails, just skip it
try {
int id = Integer.parseInt(tokens[1]);
long timeInMillis = Long.parseLong(tokens[2]);
if (tokens[0].equals(System.RTC)){
rtcHistory.put(id, new Date(timeInMillis));
} else if (tokens[0].equals(System.ALM)){
almHistory.put(id, new Date(timeInMillis));
}
} catch (Exception e){
log.error("Unable to parse exchange history file at line:" + lineNumber, e);
}
lineNumber++;
}
} catch (FileNotFoundException e){ // try to create a new file in case it doesn't exist
log.warn("No exchange history file found at " + path);
try {
file.createNewFile();
log.info("Created new exchange history file at " + path);
} catch (IOException ioe){
log.error("Unable to create exchange history file at " + path
+ ". Exchange session info won't be saved", ioe);
}
// return an empty history list cause there are no records in new file
return exchHist;
} catch (IOException e) {
log.error("Unable to read exchange history file at " + path
+ ". All items will be synchronized anew", e);
return exchHist;
} finally{
if (reader != null){
try {
reader.close();
} catch (IOException e) {
log.error("Unable to close input stream. Resource leak possible", e);
}
}
}
return exchHist = new ExchangeHistory(rtcHistory, almHistory);
}
new BufferedReader(new FileReader())
instead ofnew BufferedReader(new InputStreamReader(new FileInputStream()))
\$\endgroup\$Reader
in as the input parameter and remove almost all resource management concerns (including closing the reader) elsewhere right away. What does it matter if the characters come from a file or http or loaded from classpath or telepathied. As long as it implementsReader
, you're good. \$\endgroup\$