我创建了一个程序,它将计算一些东西并将信息存储到一个哈希表中。我希望它在下次运行时恢复存储在 hashTable 中的先前值并恢复。所以我问如何将对象保存到文件中?
在我的代码中,我使用的是 FileInputStream 和 FileOutputStream。到目前为止,这是我的代码的一个片段:
@SuppressWarnings("unchecked")
private void obtainSaveFile(){
String file = new String("./saveFile.txt");
try{
//Create the file if it doesn't exist
if( !( (new File(file)).exists() ) ){
//Create new empty file
(new File(file)).createNewFile();
//Creates a fresh new hashTable
hashTable = new QuadraticProbingHashTable<TicTacToeBoard>();
}
else{
//Obtain the hashTables saved config.txt file
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
//Obtain the previously saved hashTable
//-----------------------------------
//This line of code gives me an error
//-----------------------------------
hashTable = (QuadraticProbingHashTable<TicTacToeBoard>)ois.readObject();
ois.close();
}
//Create save file configs.txt
FileOutputStream fos = new FileOutputStream(file);
saveFile = new ObjectOutputStream(fos);
}catch(Exception e){
e.printStackTrace();
//Creates a fresh new hashTable
//This line of code gives me an error
hashTable = new QuadraticProbingHashTable<TicTacToeBoard>();
}
}
最初,当没有文件时,它运行良好。但在那之后,它一直给我错误。当我从文件中获取一个对象并将其转换为 QuadraticProbingHashTable 并将其设置为等于 hashTable 时,它不喜欢。
此外,这是作为错误输出的内容:
java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: proj4.QuadraticProbingHashTable$HashEntry
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readArray(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
at java.io.ObjectInputStream.readSerialData(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at proj4.TicTacToeSolver.obtainSaveFile(TicTacToeSolver.java:308)
at proj4.TicTacToeSolver.solve(TicTacToeSolver.java:120)
at proj4.Main.main(Main.java:41)
Caused by: java.io.NotSerializableException: proj4.QuadraticProbingHashTable$HashEntry
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeArray(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at proj4.TicTacToeSolver.solve(TicTacToeSolver.java:246)
... 1 more
Exception in thread "main" java.lang.NullPointerException
at proj4.TicTacToeSolver.solve(TicTacToeSolver.java:246)
at proj4.Main.main(Main.java:41)