I want to read a particular value from LinkedHashMap written in a .txt file, but is showing "java.io.StreamCorruptedException: invalid stream header: 7B495020"
For writing in LinkedHashMap i tried the method;
public void WriteBasicInfo(String name, String pass) throws IOException, ParseException {
Map<String, String> m;
try {
m = new LinkedHashMap<String, String>();
m.put("Name", name);
m.put("Password", pass);
BufferedWriter bw = new BufferedWriter(new FileWriter(FILE_NAME, false));
bw.write(m.toString());
bw.flush();
bw.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
And it successfully writes in file. But when Iam trying to read the above hashmap using this method
public void readBasicInfo() throws IOException, ParseException, InvocationTargetException, ClassNotFoundException
{
ObjectInputStream is = new ObjectInputStream(new FileInputStream(FILE_NAME));
Map<String, String> myMap=(LinkedHashMap<String, String>) is.readObject();
for(Map.Entry<String,String> m :myMap.entrySet()){
System.out.println(m.getKey()+" : "+m.getValue());
// String val1=m.get("Name");
}
ois.close();
}
it is showing "java.io.StreamCorruptedException: invalid stream header: 7B495020" , and no data is read
I tried to read all the entries written in hashmap, to check whether it is reading or not; but actually I just want read only "name" entry stored in hashmap.
You are simply: writing as string, but reading back expecting a binary serialized object!
You know, that is like: you put an egg in a box, and then you expect you can open that box and pour milk from it into a glass! That wont work.
Here:
bw.write(m.toString());
You write the map into that file as raw string. This means that your file now contains human readable strings!
But then you do:
Map<String, String> myMap=(LinkedHashMap<String, String>) is.readObject();
Which expects that the file contains serialized objects.
Long story short, these are your options:
My recommendation: go for option 2, or 3. 2 adds a dependency to a 3rd party library, but I think it is the more "common" practice these days.