Write HashMap to Text File in Java Example

This example shows how to write HashMap object to a text file in Java such that each line of the text file contains a key and a value separated by a colon or any other separator of your choice.

How to write a HashMap object to a text file in Java?

The HashMap class in Java implements the Serializable interface so that its objects can be written or serialized to a file using the ObjectOutputStream. However, the output file it produces is not in the human-readable format and may contain junk characters.

If you want to write a HashMap object to a plain text file, you need to write custom code. In the below given example, I am going to write all the keys and values of a map object to a file such that each line of the file will contain a key-value pair separated by a colon (“:”).

The method is simple, iterate the HashMap entries and write the key followed by a colon followed by the value as given below.

Output file content

Important Note:

The above example does not work for all types of objects including objects of a custom class. If you want to write a map object having the key or value of a custom class, you can first convert the object to JSON and then write JSON object to a text file.

If you want to read the text file back to the HashMap object, please refer to how to read text file into HashMap example.

If you want to write a HashMap object to a file and later want to retrieve the file contents in a HashMap object, you should use the ObjectOutputStream to serialize it instead of using the above code. The only difference is that the output file will not be in the human-readable format.

This example is a part of the HashMap in Java tutorial.

Please let me know your views in the comments section below.

About the author



My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *