顺序写入对象的另一种方法是将它们存储在集合(例如HashMap)中,因为可以序列化集合。这可能会使检索时的管理起来更容易一些,尤其是当您有许多要序列化/反序列化的对象时。以下代码演示了这一点:
String first = "first"; String second = "second"; HashMap<String, Object> saved = new HashMap<String, Object>(); saved.put("A", first); saved.put("B", second); try { FileOutputStream fos = new FileOutputStream("test.obj"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(saved); oos.flush(); oos.close(); fos.close(); FileInputStream fis = new FileInputStream("test.obj"); ObjectInputStream ois = new ObjectInputStream(fis); HashMap<String,Object> retreived = (HashMap<String,Object>)ois.readObject(); fis.close(); System.out.println(retreived.get("A")); System.out.println(retreived.get("B")); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); }}运行此命令将导致:
firstsecond



