Tutorial :java hashmap query



Question:

Im reading values from a file and storing these values in a hashmap, using a bufferedreader, in the following manner --

while((String str=buffread.readLine()).length()>1)              {                  hashMap.put(str.substring(0,5),str);                }  

I can also verify that the hashmap has all data that was initially present in the file.

Now, Im trying to write the values of exact hashmap to another file in the following manner --

FileWriter outFile = new FileWriter("file path");           PrintWriter out = new PrintWriter(outFile);           Set entries = hashMap.entrySet();            Iterator entryIter = entries.iterator();            while (entryIter.hasNext()) {               Map.Entry entry = (Map.Entry)entryIter.next();               Object value = entry.getValue();  // Get the value.               out.println(value.toString());            }  

But this seems to write lesser number of entries into the file than the value of hashMap1.size() or essentially, the number of entries that it initially read from the source file.

Though I have a hunch that its because of the Printwriter and filewriter, if anyone could point me to why this issue is occurring, it would be of great help.

Regards p1nG


Solution:1

Perhaps you left this out of the code you posted, but are you explicitly calling flush() and close() on the PrintWriter/FileWriter objects when you are done with them?

Each call to println() does not necessarily cause a line to be written to the underlying OutputStream/file.


Solution:2

Unless the first 5 characters on every line of your source file are unique, this line

hashMap.put(str.substring(0,5),str);  

will ensure you're overwriting some entries in the Map.


Solution:3

There is a possibility that something fails when writing to file:

Methods in this (PrintWriter) class never throw I/O exceptions. The client may inquire as to whether any errors have occurred by invoking checkError().

In general, I don't think it's a problem with HashMap, as you said that the data was read correctly.


Solution:4

You can't possibly read a file correctly with that code. You have to check the result of readLine() for null before you do anything else with it, unless you like catching NullPointerExceptions of course.


Solution:5

You don't need the Iterator at this point, just use a keyset at iterate this

Set<String> keys = hashMap.keySet();  for(String key : keys){   out.println(hashMap.get(key));  }  

should do it.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »