提示
Java IO ObjectInputStream 使用示例。@ermo
# ObjectInputStream 使用示例
ObjectInputStream
用于将对象读入程序中,在对象的流操作上同样比 DataInputStream
更加方便灵活。
使用 ObjectInputStream
的前提也使用被读取的对象要继承 Serializable
接口。
主要的构造方法有:
public ObjectInputStream(InputStream in)
protected ObjectInputStream()
ObjectInputStream
是一个装饰类,继承了 FilterInputStream
类,同时实现了 DataInput
接口。
看一个从文件中读取对象的例子,例子中的 write-order.txt 文件使用的就是 ObjectOutputStream
实例中输出的文件。
public static void readOrder() throws IOException, ClassNotFoundException {
String filepath = "src/main/resources/write-order.txt";
try (ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(filepath)))) {
Order order = (Order)in.readObject();
System.out.println(order.toString());
}
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
readOrder();
}
执行程序,打印内容为:
Order{orderNo='O123', orderType=1, orderAmount=99.99}
看一个读取对象集合的示例:
public static void readOrders() throws IOException, ClassNotFoundException {
String filepath = "src/main/resources/write-orders.txt";
try (ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(filepath)))) {
List<Order> orders = (List<Order>)in.readObject();
for (Order order : orders) {
System.out.println(order.toString());
}
}
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
readOrders();
}
输出内容为:
Order{orderNo='O456', orderType=1, orderAmount=99.99}
Order{orderNo='O789', orderType=2, orderAmount=88.88}