class Person implements Serializable {
private String name = "Tom";
private int age = 16;
public Person () {
}
public Person(String name ,int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", getClass()=" + getClass() + ", hashCode()=" + hashCode()
+ ", toString()=" + super.toString() + "]";
}
}
private static String filename = String.format("D:%s99_temp%sseri", File.separator,File.separator);
private static void serializable (Person person ) {
try {
ObjectOutputStream oOutputStream = new ObjectOutputStream(new FileOutputStream(filename));
oOutputStream.writeObject(person);
oOutputStream.close();
} catch (FileNotFoundException e) {
// TODO auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO auto-generated catch block e.printStackTrace(); } }
private static void deserializable() {
try {
ObjectInputStream oInputStream = new ObjectInputStream(new FileInputStream(filename));
Person person = (Person) oInputStream.readObject();
System.out.println(person.toString());
oInputStream.close();
} catch (ClassNotFoundException e) {
// TODO auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO auto-generated catch block e.printStackTrace(); } }
public static void main(String[] args) {
serializable(new Person());
deserializable();
}
No. | Class used, interface | Remarks |
---|---|---|
1.Data class inheritance | Serializable | Serialize |
3.Serialize | ObjectOutputStream | Export object |
3.Serialize | FileOutputStream | Export file |
4.Anti-serialize | ObjectInputStream | Loading an object |
4.Anti-serialize | FileInputStream | Read file |
Recommended Posts