4 回答

TA貢獻1796條經驗 獲得超4個贊
在我反序列化Hashtable并打印它之后,我得到了{}.
我究竟做錯了什么?
此代碼是從您的 MCVE 代碼復制而來的。您已經將其編輯掉了,但我相信這個或類似的東西是您問題的真正原因。
public static void write(String s) throws FileNotFoundException, IOException
{
list = new Hashtable<Date,String>();
FileOutputStream fos = new FileOutputStream(s);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(list);
}
您應該調用close(),oos但這不是真正的問題。
(丟失close() 可能會導致序列化文件為空或不完整/損壞,但這不會導致您讀回空Hashtable的 .new FileOutputStream(s)
真正的問題是方法的第一條語句。您無條件地將一個新的空值分配Hashtable給list. 然后你在寫它。所以(自然地)當你讀回你寫入文件的內容時,你會Hashtable再次得到一個空的。這就是{}你所看到的意思。
簡而言之,您的代碼正在寫出一個空表并再次讀回。Hashtable序列化正在按預期工作。

TA貢獻1841條經驗 獲得超3個贊
您是否正在向文件寫入任何內容,因為 write 方法將 String 作為參數,但您尚未指定要寫入哪個文件。嘗試:
public static void write(File f) throws FileNotFoundException, IOException
{
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
Hashtable<Date, String> list = new Hashtable<>();
list.put(YourDateObject, "String");
oos.writeObject(list);
}

TA貢獻1770條經驗 獲得超3個贊
這是代碼示例:
public class Main {
/**
* File name
*/
private final static String FILENAME = "test.bin";
/**
* Entry point
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
Hashtable<Date, String> original = new Hashtable<>();
// write some data to hashtable
for (int i = 0; i < 3; i ++) {
original.put(new Date(), String.valueOf(i));
TimeUnit.MILLISECONDS.sleep(100);
}
// serialize
write(FILENAME, original);
// deserialize
Hashtable<Date, String> restored = read(FILENAME);
// compare results
System.out.println(restored);
System.out.println(restored);
}
/**
* Deserialization
*
* @param filename
* @return
* @throws IOException
* @throws ClassNotFoundException
*/
public static Hashtable<Date, String> read(String filename) throws IOException, ClassNotFoundException {
try (ObjectInputStream oos = new ObjectInputStream(new FileInputStream(filename))) {
return (Hashtable<Date, String>) oos.readObject();
}
}
/**
* Serialization
*
* @param filename
* @param list
* @throws FileNotFoundException
* @throws IOException
*/
public static void write(String filename, Hashtable<Date, String> list) throws FileNotFoundException, IOException {
try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename))) {
oos.writeObject(list);
}
}
}
添加回答
舉報