标签:计算 cep int 年龄 ted serial pre setname rgs
用序列化来存储对象。
先定义一个用来序列化的类:
package io.xuliehua;
import java.io.*;
public class Student implements Serializable{
private String name;
private String ID;
private int age;
private String specialty;
public Student(String name, String ID, int age, String specialty){
this.name=name;
this.ID=ID;
this.age=age;
this.specialty=specialty;
}
public Student(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getID() {
return ID;
}
public void setID(String iD) {
ID = iD;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSpecialty() {
return specialty;
}
public void setSpecialty(String specialty) {
this.specialty = specialty;
}
public String toString(){
return "姓名:"+name+" 学号:"+ID+" 年龄:"+age+" 专业:"+specialty;
}
}
package io.xuliehua;
import java.io.*;
public class ObjectFileTest {
public static void main(String[] args) {
Student st = new Student("周勇","20140101",18,"计算机");
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("save.dat"));
out.writeObject(st);
out.close();
ObjectInputStream in = new ObjectInputStream(new FileInputStream("save.dat"));
Student pupil = (Student)in.readObject();
in.close();
System.out.println(pupil);
System.out.println("姓名:"+pupil.getName());
System.out.println("学号:"+pupil.getID());
System.out.println("年龄:"+pupil.getAge());
System.out.println("专业:"+pupil.getSpecialty());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block e.printStackTrace();
}
}
}
标签:计算 cep int 年龄 ted serial pre setname rgs
原文地址:http://www.cnblogs.com/m2492565210/p/7466153.html