java中如何实现序列化对象ObjectInputStream和ObjectOutputStream?
1个回答
展开全部
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Student implements Serializable
{
String name;
int age;
public Student(String name,int age)
{
this.name=name;
this.age=age;
}
}
public class ObjectTest
{
public static void main(String[] args)
{
try
{
FileOutputStream fos=new FileOutputStream("F:\\io\\abc.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
Student s=new Student("Tom",21);
oos.writeObject(s);
oos.close();
fos.close();
FileInputStream fis=new FileInputStream("F:\\io\\abc.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
Student tom=(Student)ois.readObject();
ois.close();
fis.close();
System.out.println("学生的姓名为:"+tom.name);
System.out.println("学生的年龄为:"+tom.age);
}
catch (FileNotFoundException e)
{
System.out.println("操作的文件不存在");
}
catch(IOException e)
{
System.out.println("发生IO操作异常");
}
catch(ClassNotFoundException e)
{
System.out.println("序列化对象的类无法找到");
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询