Java 中序列化与反序列化,看这篇就够了!

/**

  • 实现了序列化接口的学生类
    */

public class Student implements Serializable {

private String name;
private char sex;
private int year;
private double gpa;
public Student() {
}
public Student(String name,char sex,int year,double gpa) {
    this.name = name;
    this.sex = sex;
    this.year = year;
    this.gpa = gpa;
}
public void setName(String name) {
    this.name = name;
}
public void setSex(char sex) {
    this.sex = sex;
}
public void setYear(int year) {
    this.year = year;
}
public void setGpa(double gpa) {
    this.gpa = gpa;
}
public String getName() {
    return this.name;
}
public char getSex() {
    return this.sex;
}
public int getYear() {
    return this.year;
}
public double getGpa() {
    return this.gpa;
}

}
把Student类的对象序列化到文件/Users/sschen/Documents/student.txt,并从该文件中反序列化,向console显示结果。期货代码如下:
public class UserStudent {

public static void main(String[] args) {
    Student st = new Student("Tom",'M',20,3.6);
    File file = new File("/Users/sschen/Documents/student.txt");
    try {
        file.createNewFile();
    }
    catch(IOException e) {
        e.printStackTrace();
    }
    try {
        //Student对象序列化过程
        FileOutputStream fos = new FileOutputStream(file);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(st);
        oos.flush();
        oos.close();
        fos.close();
        //Student对象反序列化过程
        FileInputStream fis = new FileInputStream(file);
        ObjectInputStream ois = new ObjectInputStream(fis);
        Student st1 = (Student) ois.readObject();
        System.out.println("name = " + st1.getName());
        System.out.println("sex = " + st1.getSex());
        System.out.println("year = " + st1.getYear());
        System.out.println("gpa = " + st1.getGpa());
        ois.close();
        fis.close();
    }
    catch(ClassNotFoundException e) {
        e.printStackTrace();
    }
    catch (IOException e) {
        e.printStackTrace();
    }
}

}
而查看文件/Users/sschen/Documents/student.txt,其内保存的内容并不是可以容易阅读的内容:
aced 0005 7372 001f 636f 6d2e 7373 6368
656e 2e53 6572 6961 6c69 7a61 626c 652e
5374 7564 656e 74f1 5dbd a4a0 3472 4d02
0004 4400 0367 7061 4300 0373 6578 4900
0479 6561 724c 0004 6e61 6d65 7400 124c
6a61 7661 2f6c 616e 672f 5374 7269 6e67
3b78 7040 0ccc cccc cccc cd00 4d00 0000
1474 0003 546f 6d

你可能感兴趣的:(java)