Java 中序列化與反序列化,看這篇就夠了!

/**html

  • 實現了序列化接口的學生類
    */

public class Student implements Serializable {this

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 {code

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 6dhtm

相關文章
相關標籤/搜索