我正在尝试将“HashMap”类型的对象写入文件并在我的程序再次运行时恢复它。但是当我尝试读取该对象并且未从文件中读取该对象时,我遇到了 EOFException。当我为 FileOutputStream 和 ObjectOutputStream 编写对象时,我使用了 flush() 和 close() 方法。我还为我的文件一起创建了 OutputStream 和 InputStream。这是我的代码:
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();
}
}
这是编写对象的代码:
table.put(NameField.getText(), IPField.getText());
try {
//writeTableToFile.reset();
writeTableToFile.writeObject(table);
writeTableToFile.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
问候,萨贾德