A problem with java Object Streams while writing to file
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 (IOExce开发者_如何学编程ption e1) {
e1.printStackTrace();
}
Regards, sajad
The file seems to be incomplete. When I look at your code, you're creating the file table.txt and try to read it immediately afterwards.
This ctor:
new FileOutputStream(tableFile)
will overwrite the file. If your read it afterwards, it will be empty (except the header information from the OOS)
EOFException
means that the file is incomplete. So it's either not flush()
ed or not close()
ed or an exception is swallowed somewhere.
精彩评论