ObjectOutputStram
类用于将Java对象的原始数据类型和图形存储到输出流,而ObjectInputStream
类用于从输入流中读取Java对象的原始数据类型和图形。
注 – 只有那些类实现
java.io.Serializable
接口的对象才能被写入流。
下面是一个演示ObjectOutputStram
和ObjectInputStream
的示例。
文件:User.java –
package com.yiibai.tutorial.io; import java.io.Serializable; /** * @author yiibai */ public class User implements Serializable { private static final long serialVersionUID = -3389363800876569458L; private int id; private String name; public User(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "ID="+this.id+" NAME="+this.name; } }
在上面的示例中,User
类实现了Serializable
接口,现在我们可以将其对象存储到输出流中。
文件:ObjectInputOutputStreamExample.java –
package com.yiibai.tutorial.io; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Date; /** * @author yiibai */ public class ObjectInputOutputStreamExample { public static void main(String[] args) { File file = new File("file.txt"); /* Write object and primitive data type to output stream */ FileOutputStream fileOutputStream = null; ObjectOutputStream outputStream = null; try { fileOutputStream = new FileOutputStream(file); outputStream = new ObjectOutputStream(fileOutputStream); // Write int value outputStream.writeInt(500); // Write date outputStream.writeObject(new Date()); // Write User object outputStream.writeObject(new User(1, "yiibai")); } catch (IOException e) { e.printStackTrace(); } finally { try { if (fileOutputStream != null) { fileOutputStream.close(); } if (outputStream != null) { outputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } /* Read object and primitive data type from input stream */ FileInputStream fileInputStream = null; ObjectInputStream objectInputStream = null; try { fileInputStream = new FileInputStream(file); objectInputStream = new ObjectInputStream(fileInputStream); // Read int int value = objectInputStream.readInt(); System.out.println(value); // Read date Date date = (Date) objectInputStream.readObject(); System.out.println(date); // Read User object User user = (User) objectInputStream.readObject(); System.out.println(user); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } finally { try { if (fileInputStream != null) { fileInputStream.close(); } if (objectInputStream != null) { objectInputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
执行上面示例代码,得到以下结果:
500 Sun Nov 06 10:21:52 IST 2016 ID=1 NAME=yiibai
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/264110.html