How to read and write a hashmap to a file


















This example is a part of the Java HashMap tutorial with examples. 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 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. Your email address will not be published. Leave a reply. How to read a text file to HashMap in Java?

I am going to use the below given text file contents for the purpose of this example. BufferedReader ;. File ;. 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.

The method is simple, iterate the HashMap entries and write the key followed by a colon followed by the value as given below. 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. Get that sorted out without the HashMap. Add a comment. Active Oldest Votes. Improve this answer. Ghazanfar Ghazanfar 1, 12 12 silver badges 21 21 bronze badges. Sign up or log in Sign up using Google.

Sign up using Facebook. Sign up using Email and Password. Post as a guest Name. Email Required, but never shown. The Overflow Blog. Podcast Making Agile work for data science. Stack Gives Back Next Methods in Java. Recommended Articles. Article Contributed By :. Easy Normal Medium Hard Expert. Writing code in comment? Please use ide. Load Comments.



0コメント

  • 1000 / 1000