- The ObjectInputStream (byte stream) and the ObjectOutputStream (byte stream)
- In addition to saving the basic data types, further comprising custom objects, since the object is defined read type Object, the need to use casts
- Serialization: the output stream,
- Deserialized: input stream
- And consistent with the data stream must be read after write, sequential read and write consistency
- Serialized object must implement the java.io.Serializable interface
-
transient: the data does not serialized data transparency (output display null), private transient String name;
// read-after-write, read and write the number of Xu consistent
public class n { public static void main(String[]args) throws IOException, ClassNotFoundException {
Into the byte array
// write serialize
ByteArrayOutputStream ByteArrayOutputStream new new OS = ();
the ObjectOutputStream the ObjectOutputStream OOS new new = (new new BufferedOutputStream The (OS));
HA FF = new new HA ( "HH", 222);oos.writeUTF("哈哈"); oos.writeChar('q'); oos.writeBoolean(false); oos.writeObject(ff); oos.flush(); byte[] datas=os.toByteArray(); oos.close(); //读取 反序列化 ObjectInputStream ois =new ObjectInputStream(new BufferedInputStream(new ByteArrayInputStream(datas))); String s=ois.readUTF(); char ch=ois.readChar(); boolean flag=ois.readBoolean(); Object str=ois.readObject(); //Object需要强制转换 //还原(判断是哪个类,然后强制转换): if (str instanceof String ) //是String类就直接转换成字符串 { String s1=(String)str; System.out.println(s1); } if(str instanceof Data) { Date d=(Date)str; System.out.println(d); } if(str instanceof ha) { ha fr=(ha)str; System.out.println(fr.getName()+fr.getSalary()); } ois.close(); } //javabean,用于封装数据 class ha implements java.io.Serializable { private transient String name; //该数据不需要序列化,数据透明 private double salary; public ha() { } public ha(String name,double salary) { this.name=name; this.salary=salary; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } }
Write to the file:
ObjectOutputStream oos=new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("D:/d/s")));
ha ff=new ha("hh",222);
oos.writeUTF("what");
oos.writeObject(ff);
oos.flush();
oos.close();
//使用时,反序列化对象
ObjectInputStream ois=new ObjectInputStream(new BufferedInputStream(new FileInputStream("D:/d/s")));
String s=ois.readUTF();
Object it=ois.readObject();
if(it instanceof ha)
{
ha q=(ha)it;
System.out.println(q.getName()+q.getSalary());
}
ois.close();
//javabean 用于封装数据
class ha implements java.io.Serializable {
private transient String name; //该数据不需要序列化,数据透明
private double salary;
public ha()
{
}
public ha(String name,double salary)
{
this.name=name;
this.salary=salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}