* 将对象(Object)序列化到文件中永久保存
* ObjectInputStream(InputStream in)
* ObjectOutputStream(OutputStream out)
* */
* ObjectInputStream(InputStream in)
* ObjectOutputStream(OutputStream out)
* */
public class ObjectStreamDemo {
public static void main(String[] args) throws Exception {
writeObject();
readObject();
}
public static void writeObject() throws Exception
{
//对象输出流,内存-->文件
ObjectOutputStream oos
= new ObjectOutputStream(new FileOutputStream("obj.txt"));
oos.writeObject(new Person("mhc",23));
oos.close();
}
public static void readObject() throws Exception
{
//对象输出流,文件-->内存
ObjectInputStream ois
= new ObjectInputStream(new FileInputStream("obj.txt"));
Person p = (Person)ois.readObject();
System.out.println(p);
}
}
//未实现Serializable接口的类将无法使其任何状态序列化或反序列化
class Person implements Serializable
{
String name;
int age;
Person(String name,int age)
{
this.name = name;
this.age = age;
}
public String toString()
{
return name+"--"+age;
}
}