/ Published in: Java
Use Scanner instead of BufferedReader and StringTokenizer for parsing the line. I see a potential for using Scanner for both use cases. But it was a major improvement to get rid of the split arrays. In addition the BufferedReader was not closed. The scanner is in the final loop. Also, use of static is highly discouraged. Object oriented approach is better and no reason to expose map or list, or the parse method. Both is now private. String expectations about file encoding. Lets assume we only handle UTF-8 files. No fishy norwegian characters.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
package com.java.test; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.StringTokenizer; /*** * input file format: * * foo|bar * foo2|bar2 * . * . */ public class Indexer { indexerMap = parseFileIntoMap(filename); } Scanner scanner = null; try { scanner.useDelimiter("[ ]+"); while (scanner.hasNext()) { if (tokenizer.countTokens() == 2) { map.put(key, value); } } throw new IllegalArgumentException("Could not load file indexing! The file "+filename+" does not exist.", e); }finally { if(scanner != null) scanner.close(); } return map; } /*** * Returns the value from the map if key is not null */ if (key == null) { return null; } else { return indexerMap.get(key); } } }