Hi, I am trying to write an Object of kind "HashMap" to a file & recover it when my program run again. But I faced with an EOFException when I try to read that object and the Object is not read from the file. I use the flush() & close() methods when I wrote the object for the FileOutputStream & ObjectOutputStream. Also I create OutputStream & InputStream together for my file. here is my code:
DataOutputStream outToFile;
DataInputStream inFromFile;
ObjectOutputStream writeTableToFile;
ObjectInputStream readTableFromFile;
File tableFile;
public DNS(){
try {
tableFile = new File("table.txt");
outToFile = new DataOutputStream(new FileOutputStream(tableFile) );
writeTableToFile = new ObjectOutputStream(outToFile);
inFromFile = new DataInputStream(new FileInputStream(tableFile));
readTableFromFile = new ObjectInputStream(inFromFile);
HashMap table2 = (HashMap) readTableFromFile.readObject();
if (table2 == null)
table=new HashMap(100);
else
table = table2;
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(EOFException e){
table=new HashMap(100);
}
catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
and here is code for writing object:
table.put(NameField.getText(), IPField.getText());
try {
//writeTableToFile.reset();
writeTableToFile.writeObject(table);
writeTableToFile.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
Regards, sajad