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) {
// Bloc catch généré automatiquement par TODO e.printStackTrace(); } catch (IOException e) { // Bloc catch généré automatiquement par TODO 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) {
// Bloc catch généré automatiquement par TODO e.printStackTrace(); } catch (IOException e) { // Bloc catch généré automatiquement par TODO e.printStackTrace(); } }
public static void main(String[] args) {
serializable(new Person());
deserializable();
}
No. | Classe utilisée, interface | Remarques |
---|---|---|
1.Héritage de classe de données | Serializable | Sérialiser |
3.Sérialiser | ObjectOutputStream | Exporter un objet |
3.Sérialiser | FileOutputStream | Exporter le fichier |
4.Anti-sérialisation | ObjectInputStream | Chargement d'un objet |
4.Anti-sérialisation | FileInputStream | Lire le fichier |
Recommended Posts