Almost every project that I work will have some sort of tab delimited file that I need to read in and return a lookup Map of it. I find myself rewrite the same method over and over again. I want to create something more generic so I don’t have to do copy and paste code all the time. From the below code, I only change line 9, and 16-19. So I only change the Map<key, value>, and the implementation of how I want to input data into the Map. Is there a way make a generic process from this, so every time I want to invoke this method, all I need is to provide my implementation of how I want to input data into Map, and somehow change the Map to a more generic type as well.
1. public Map<String, PackageLog> readAllLogsIntoMap(File file){
2. if (!file.exists())
3. {
4. return new HashMap <String, PackageLog> ();
5. }
6. BufferedReader reader = null;
7. FileReader fileReader = null;
8. String data = null;
9. Map <String, PackageLog> resultMap = new HashMap <String, PackageLog> ();
10. try
11. {
12. fileReader = new FileReader(file);
13. reader = new BufferedReader(fileReader);
14. while ((data = reader.readLine()) != null)
15. {
16. PackageLog pl = new PackageLog(data);
17. if(!pl.getPdfName().equals("")){
18. resultMap.put(pl.getPdfName(), pl);
19. }
20. }
21. } catch(Exception e){
22.
23. }
24. finally
25. {
26. try{
27. if (reader != null) reader.close();
28. if (fileReader != null) fileReader.close();
29. }catch(IOException ioe){
30.
31. }
32. }
33. return resultMap;
34. }
For instance:
And a possible use:
Take into account you only need the
newMap()method if you want to provide different map implementations. You could well donew HashMap<K, V>()inside the generified class.You might also want to define hook methods (overridable, maybe-empty methods) for handling exceptions.