Error: Exception in thread AWT-EventQueue-0 java.lang.ClassC



是否可以从单个文件中读取不同类型的对象?

是否可以从单个文件中读取不同类型的对象…?

当然是!下面的输出证明:

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,但可以随意调整代码以使用实际文件来确认工作。

相关内容

最新更新