public class WriteObject
{
public static void main(String[] args)
{
ObjectOutputStream oos = null;
try
{
//创建一个ObjectOutputStream输出流
oos = new ObjectOutputStream(
new FileOutputStream("object.txt"));
Person per = new Person("孙悟空", 500);
//将per对象写入输出流
oos.writeObject(per);
}
catch (IOException ex)
{
ex.printStackTrace();
}
finally
{
try
{
if (oos != null)
oos.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
}
public class Person
implements java.io.Serializable
{
private String name;
private int age;
public Person(String name , int age)
{
System.out.println("有参数的构造器");
this.name = name;
this.age = age;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return this.name;
}
public void setAge(int age)
{
this.age = age;
}
public int getAge()
{
return this.age;
}
}
public class ReadObject
{
public static void main(String[] args)
{
ObjectInputStream ois = null;
try
{
//创建一个ObjectInputStream输出流
ois = new ObjectInputStream(
new FileInputStream("object.txt"));
//从输入流中读取一个Java对象,并将其强制类型转换为Person类
Person p = (Person)ois.readObject();
System.out.println("名字为:" + p.getName()
+ "\n年龄为:" + p.getAge());
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
try
{
if (ois != null)
ois.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
}