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.
Serialization: It is a process of writing an Object into a file along with its attributes and content. It internally converts the object into a stream of bytes.
De-Serialization: It is a process of reading the Object and its properties from a file along with the Object’s content.
If we want to write a HashMap object to a plain text file, we need a simple and understandable code to write on the HashMap and then insert the Map into the Text File. We can write the code in the form of key-Value Pair of a map Object to a File and each line File will contain the Key-Value Pair
- In the below class we are storing the HashMap content in a hashmap.ser serialized file.
- Once when we run the below code it would produce a hashmap.ser file. This file would be used in the next class for de-serialization.
- The hashmap.ser serialised file can be Stored to any Location with describing it’s Location Like Below
- So we need the Location to write the HashMap in it.
- So for that need to Provide the External Location to Store the HashMap
final static String outputFilePath = "F:/Serialisation/write.txt";
Create the HashMap of String Key and String Value Pair
HashMap<String, String> map = new HashMap<String, String>();
Create the File Object:
File file = new File(outputFilePath);
Using the file object we will write the HashMap input using the function BufferedWriter(File_Path)
bf = new BufferedWriter( new FileWriter(file));
and then at last close the File
Writing to File
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.