How to write and read a file with a HashMap?
since HashMap
implements Serializable
interface, you can simply use ObjectOutputStream
class to write whole Map
to file, and read it again using ObjectInputStream
class
below simple code that explain usage of ObjectOutStream
and ObjectInputStream
import java.util.*;
import java.io.*;
public class A{
HashMap<String,String> hm;
public A() {
hm=new HashMap<String,String>();
hm.put("1","A");
hm.put("2","B");
hm.put("3","C");
method1(hm);
}
public void method1(HashMap<String,String> map) {
//write to file : "fileone"
try {
File fileOne=new File("fileone");
FileOutputStream fos=new FileOutputStream(fileOne);
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(map);
oos.flush();
oos.close();
fos.close();
} catch(Exception e) {}
//read from file
try {
File toRead=new File("fileone");
FileInputStream fis=new FileInputStream(toRead);
ObjectInputStream ois=new ObjectInputStream(fis);
HashMap<String,String> mapInFile=(HashMap<String,String>)ois.readObject();
ois.close();
fis.close();
//print All data in MAP
for(Map.Entry<String,String> m :mapInFile.entrySet()){
System.out.println(m.getKey()+" : "+m.getValue());
}
} catch(Exception e) {}
}
public static void main(String args[]) {
new A();
}
}
or if you want to write data as text to file you can simply iterate through Map
and write key and value line by line, and read it again line by line and add to HashMap
import java.util.*;
import java.io.*;
public class A{
HashMap<String,String> hm;
public A(){
hm=new HashMap<String,String>();
hm.put("1","A");
hm.put("2","B");
hm.put("3","C");
method2(hm);
}
public void method2(HashMap<String,String> map) {
//write to file : "fileone"
try {
File fileTwo=new File("filetwo.txt");
FileOutputStream fos=new FileOutputStream(fileTwo);
PrintWriter pw=new PrintWriter(fos);
for(Map.Entry<String,String> m :map.entrySet()){
pw.println(m.getKey()+"="+m.getValue());
}
pw.flush();
pw.close();
fos.close();
} catch(Exception e) {}
//read from file
try {
File toRead=new File("filetwo.txt");
FileInputStream fis=new FileInputStream(toRead);
Scanner sc=new Scanner(fis);
HashMap<String,String> mapInFile=new HashMap<String,String>();
//read data from file line by line:
String currentLine;
while(sc.hasNextLine()) {
currentLine=sc.nextLine();
//now tokenize the currentLine:
StringTokenizer st=new StringTokenizer(currentLine,"=",false);
//put tokens ot currentLine in map
mapInFile.put(st.nextToken(),st.nextToken());
}
fis.close();
//print All data in MAP
for(Map.Entry<String,String> m :mapInFile.entrySet()) {
System.out.println(m.getKey()+" : "+m.getValue());
}
}catch(Exception e) {}
}
public static void main(String args[]) {
new A();
}
}
NOTE: above code may not be the fastest way to doing this task, but i want to show some application of classes
See ObjectOutputStream , ObjectInputStream, HashMap, Serializable, StringTokenizer
HashMap
implements Serializable
so you can use normal serialization to write hashmap to file
Here is the link for Java - Serialization example
The simplest solution that I can think of is using Properties class.
Saving the map:
Map<String, String> ldapContent = new HashMap<String, String>();
Properties properties = new Properties();
for (Map.Entry<String,String> entry : ldapContent.entrySet()) {
properties.put(entry.getKey(), entry.getValue());
}
properties.store(new FileOutputStream("data.properties"), null);
Loading the map:
Map<String, String> ldapContent = new HashMap<String, String>();
Properties properties = new Properties();
properties.load(new FileInputStream("data.properties"));
for (String key : properties.stringPropertyNames()) {
ldapContent.put(key, properties.get(key).toString());
}
EDIT:
if your map contains plaintext values, they will be visible if you open file data via any text editor, which is not the case if you serialize the map:
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.ser"));
out.writeObject(ldapContent);
out.close();
EDIT2:
instead of for loop (as suggested by OldCurmudgeon) in saving example:
properties.putAll(ldapContent);
however, for the loading example this is the best that can be done:
ldapContent = new HashMap<Object, Object>(properties);