我想從.dat文件中檢索多個hashmaps 但是它只給我第一個存儲!反序列化HashMap dosent給我所有的元素
public class TestSerialize
{
public static void main(String args[]) throws IOException
{
HashMap<String, String> students = new HashMap<String, String>();
// This part I changed everytime to keep the data stored in "students.dat"
// I want to retrieve all the keys that have been run
students.put("22", "xxx");
students.put("33", "yyy");
ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream("students.dat", true));
out.writeObject(students);
out.close();
}
}
下面的代碼是用來反序列化
public class TestSerialize2
{
public static void main(String args[]) throws IOException, ClassNotFoundException
{
ObjectInputStream in = new ObjectInputStream(
new FileInputStream("students.dat"));
HashMap<String, String> students = new HashMap<String, String>();
students = (HashMap<String, String>) in.readObject();
in.close();
for (String s : students.keySet())
System.out.println(s);
}
}
我希望這是明確的..
(在萬阿英,蔣達清出現運行(TestSerialize類惠蔭)第二次與提供不同的密鑰學生..(TestSerialize2類)的輸出將是舊的值只有22,33)希望這是幫助
在您的意見我試試這個: 但同樣的問題仍然存在!
package week8;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
public class TestSerialize
{
\t public static void main(String args[]) throws IOException, ClassNotFoundException
\t {
\t \t HashMap<String, String> students = new HashMap<String, String>();
\t \t // This part I changed everytime to keep the data stored in "students.dat"
\t \t // I want to retrieve all the keys that have been run
\t \t students.put("66", "xxx");
\t \t students.put("99", "yyy");
\t \t ObjectOutputStream out = new ObjectOutputStream(
\t \t \t \t new FileOutputStream("students.dat", true));
\t \t File file = new File("students.dat");
\t \t if (file.length() == 0){
\t \t \t System.out.print("sss");
\t \t \t out.writeObject(students);
\t \t \t out.close();
\t \t }else
\t \t {
\t \t \t students =readThenWrite(students);
\t \t \t for (String s : students.keySet())
\t System.out.println(s);
\t \t \t
\t \t \t out.writeObject(students);
\t \t \t out.close();
\t \t \t
\t \t \t
\t
\t \t }
\t }
\t private static HashMap<String, String> readThenWrite(HashMap<String, String> students) {
HashMap<String, String> ss = new HashMap<String, String>();
ObjectInputStream in;
\t \t try {
\t \t \t in = new ObjectInputStream(
\t \t \t new FileInputStream("students.dat"));
\t \t
\t \t ss = (HashMap<String, String>) in.readObject();
\t \t
\t \t in.close();
\t \t for (String s : students.keySet())
\t \t ss.put(s, students.get(s));
\t \t
\t \t
\t \t
\t \t
\t \t } catch (IOException | ClassNotFoundException e) {
\t \t \t e.printStackTrace();
\t \t }
\t \t
\t \t return ss;
\t }
}
適用於我(Linux,Java 8)。 – Robert
您提供的代碼無法在我們的機器上重現問題。你能重現嗎?你真的只是使用這個代碼?在保存之前,也許你還有其他一些類操作你的設置...因爲除了代碼中的一些缺陷之外,它看起來是正確的。 – Zabuza
完美的作品 –