序列化流:ObjectOutputStream
反序列化流:ObjectInputStream
序列化的前提是要序列化的时候必须实现Serializable接口
静态不能序列化,因为静态不属于对象
package com.oracle.demo02; import java.io.Serializable; public class Person implements Serializable { /** * */ private static final long serialVersionUID = 1L; //不想被序列化,所以加上transient关键字 private transient String name; //不想被序列化,也可以加上静态修饰static private static int age; public Person(String name, int age) { super(); this.name = name; this.age = age; } public Person() { super(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } }
package com.oracle.demo02; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class Demo01 { public static void main(String[] args) throws IOException, ClassNotFoundException { write(); } public static void write() throws IOException{ //明确目的地(将一个对象写到文件里面去 先写后读) FileOutputStream fos=new FileOutputStream("D:\java\person.txt"); //创建对象 Person p=new Person("zhaoyun",666); //创建序列化流 ObjectOutputStream oos=new ObjectOutputStream(fos); //将person对象写入文件中 oos.writeObject(p); //释放资源 oos.close(); } }
package com.oracle.demo02; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class Demo01 { public static void main(String[] args) throws IOException, ClassNotFoundException { read(); } //反序列化的方法 public static void read() throws ClassNotFoundException, IOException{ //明确数据源(将一个对象写到文件里面去 先读后写) FileInputStream fis=new FileInputStream("D:\java\person.txt"); //创建反序列化流 ObjectInputStream ois=new ObjectInputStream(fis); //将文件中的对象读到person对象中 Person p=(Person)ois.readObject(); System.out.println(p); //释放资源 ois.close(); } }
不想被序列化,也可以加上静态修饰static
不想被序列化,所以加上transient关键字