Error: Exception in thread AWT-EventQueue-0 java.lang.ClassCastException
Error: Exception in thread AWT-EventQueue-0 java.lang.ClassCastException
是否可以从单个文件中读取不同类型的对象?
Is it possible to read different type objects from a single file..?
当然是!这是证明的输出:
Object: 42 // Integer
Object: The quick brown fox jumps over the lazy dog // String
Object: 42.001 // Double
这是用于上述输出的源代码:
public class ObjectSerialization {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(new Integer(42));
oos.writeObject("The quick brown fox jumps over the lazy dog");
oos.writeObject(new Double(42.001));
oos.flush();
oos.close();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
Object o;
o = ois.readObject();
System.out.println("Object: " + o);
o = ois.readObject();
System.out.println("Object: " + o);
o = ois.readObject();
System.out.println("Object: " + o);
}
}
眼尖的人可能会注意到示例中没有涉及 File
,但可以随意调整代码以使用实际文件来确认它 也 有效。
是否可以从单个文件中读取不同类型的对象?
Is it possible to read different type objects from a single file..?
当然是!这是证明的输出:
Object: 42 // Integer
Object: The quick brown fox jumps over the lazy dog // String
Object: 42.001 // Double
这是用于上述输出的源代码:
public class ObjectSerialization {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(new Integer(42));
oos.writeObject("The quick brown fox jumps over the lazy dog");
oos.writeObject(new Double(42.001));
oos.flush();
oos.close();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
Object o;
o = ois.readObject();
System.out.println("Object: " + o);
o = ois.readObject();
System.out.println("Object: " + o);
o = ois.readObject();
System.out.println("Object: " + o);
}
}
眼尖的人可能会注意到示例中没有涉及 File
,但可以随意调整代码以使用实际文件来确认它 也 有效。