【题目】
1.编写一个程序,运行Java控制台程序,检测本地是否保存学生对象(反序列化),如果保存,则输出学生信息,如果没有保存,则通过学生类Student创建一个学生对象,将学生信息输出并保存到本地文件中(序列化)。
【编码实现】
学生类:
/**
* @author HackerAC(Written by Mr.XuFufang)
*/
import java.io.Serializable;
public class Student implements Serializable{
private static final long serialVersionUID = 1L;
private String name;
private char sex;
public Student(String name, char sex) {
this.name = name;
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Student [name=" + name + ", sex=" + sex + "]";
}
}
测试类:
/**
* 反序列化和序列化
* @author HackerAC(Written by Mr.XuFufang)
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Task03 {
public static void main(String[] args) {
File file = new File("F:\\test\\Student.txt");
FileInputStream fis = null;
ObjectInputStream ois = null;
FileOutputStream fos = null;
ObjectOutputStream oos = null;
Student stu = null;
try {
fis = new FileInputStream(file);
ois = new ObjectInputStream(fis);
stu = (Student) ois.readObject();
} catch (FileNotFoundException e1) {
System.out.println("文件不存在!");
System.exit(1);
} catch (IOException e) {
System.out.println("反序列化失败:本地文件中不存在Student对象!");
} catch (ClassNotFoundException e) {
System.out.println("反序列化失败:本地文件中不存在Student对象!");
}
try {
fos = new FileOutputStream(file);
oos = new ObjectOutputStream(fos);
if (stu instanceof Student) {
System.out.println("反序列化成功!");
System.out.println(stu);
} else {
System.out.println("开始写入新的学生对象!");
stu = new Student("序列化", '男');
oos.writeObject(stu);
oos.flush();
System.out.println("序列化成功:对象信息写入完成!");
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
if (ois != null) {
ois.close();
}
if (fos != null) {
fos.close();
}
if (oos != null) {
oos.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}