Write HashMap to a Text File in Java
Last Updated :
28 Dec, 2020
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
Approach
- 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
bf.close();
Writing to File
Java
import java.io.*;
import java.util.*;
class GFG {
final static String outputFilePath
= "F:/Serialisation/write.txt" ;
public static void main(String[] args)
{
HashMap<String, String> map
= new HashMap<String, String>();
map.put( "rohit" , "one" );
map.put( "Sam" , "two" );
map.put( "jainie" , "three" );
File file = new File(outputFilePath);
BufferedWriter bf = null ;
try {
bf = new BufferedWriter( new FileWriter(file));
for (Map.Entry<String, String> entry :
map.entrySet()) {
bf.write(entry.getKey() + ":"
+ entry.getValue());
bf.newLine();
}
bf.flush();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
bf.close();
}
catch (Exception e) {
}
}
}
}
|
Output:
Share your thoughts in the comments
Please Login to comment...