Javaシーケンス化の5:付録1最も簡単なシーケンス化コード


import java.io.Serializable;

public class Person implements Serializable {

 private static final long serialVersionUID = 2356129180978015792L;
 private String name;
 private int age;

 public Person() {

 }

 public Person(String str, int n) {
  System.out.println("Inside Person's Constructor");
  name = str;
  age = n;
 }

 String getName() {
  return name;
 }

 int getAge() {
  return age;
 }
}
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializeToFlatFile {
 public static void main(String[] args) {
  SerializeToFlatFile ser = new SerializeToFlatFile();
  ser.savePerson();
  ser.restorePerson();
 }

 public void savePerson() {
  Person myPerson = new Person("Jay", 24);
  try {
   FileOutputStream fos = new FileOutputStream(
     "C:\\Documents and Settings\\l_huiqing\\デスクトップ\\ \\serial\\myPerson.txt");
   ObjectOutputStream oos = new ObjectOutputStream(fos);
   System.out.println("Person--Jay,24---Written");
   System.out.println("Name is: " + myPerson.getName());
   System.out.println("Age is: " + myPerson.getAge());

   oos.writeObject(myPerson);
   oos.flush();
   oos.close();
  } catch (Exception e) {
   // TODO: handle exception
   e.printStackTrace();
  }
 }

 public void restorePerson() {
  try {
   FileInputStream fis = new FileInputStream(
     "C:\\Documents and Settings\\l_huiqing\\デスクトップ\\ \\serial\\myPerson.txt");
   ObjectInputStream ois = new ObjectInputStream(fis);

   Person myPerson = (Person) ois.readObject();
   System.out.println("
--------------------
"); System.out.println("Person--Jay,24---Restored"); System.out.println("Name is: " + myPerson.getName()); System.out.println("Age is: " + myPerson.getAge()); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } }