activelearner
activelearner

Reputation: 7775

Java - Writing a treemap to a text file

I have a treemap called 'sortMap' which contains some keys with respective values. I am trying to write a treemap to a text file as follows.

String aggFileName = "agg-"+String.valueOf("06.txt");
FileWriter fstream = new FileWriter(aggFileName);
BufferedWriter out = new BufferedWriter(fstream);

for (Map.Entry<String, String> entry : sortMap.entrySet()) {
     System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); //this statement prints out my keys and values
     out.write(entry.getKey() + "\t" + entry.getValue());
     System.out.println("Done");

The problem that I am facing is that I am ending up with a blank file although the print statements in my code show that I am successfully iterating over the treemap. What could I be doing wrong?

Upvotes: 1

Views: 5266

Answers (1)

Maghoumi
Maghoumi

Reputation: 3390

When writing to a file, the file needs to be flushed and closed after all writing operation is done. Mostly just calling close() is sufficient, but if you want the changes to be available in the file at the end of each iteration you need to call the flush() function on the IO object.

Most IO objects have a buffer which is a temporary space for storing whatever value is being written to them. When this buffer is flushed, they write their content to the stream they are working with. Your code should be as follows:

String aggFileName = "agg-"+String.valueOf("06.txt");
FileWriter fstream = new FileWriter(aggFileName);
BufferedWriter out = new BufferedWriter(fstream);

for (Map.Entry<String, String> entry : sortMap.entrySet()) {
     System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); //this statement prints out my keys and values
     out.write(entry.getKey() + "\t" + entry.getValue());
     System.out.println("Done");
     out.flush();   // Flush the buffer and write all changes to the disk
 }

out.close();    // Close the file

Upvotes: 2

Related Questions