问题描述
是否可以从单个文件中读取不同类型的对象?
解决方法
是否可以从单个文件中读取不同类型的对象..?
当然可以!这是证明的输出:
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
,但可以随意修改代码以使用实际文件来确认它也有效。 >