Javaシーケンス化と逆シーケンス化の簡単な例
3128 ワード
1.JavaBeanクラスの作成
作成されたルール:
プライベートメンバー変数がメンバー変数に対して操作する共通get/setメソッドSerializableインタフェースを実現するには必ず公有無参の構造方法がある
2.シーケンス化
3.逆シーケンス
public class People {
private String name;
private int age;
private char sex;
public People() {
}
public People(String name, int age, char sex) {
super();
this.name = name;
this.age = age;
this.sex = sex;
}
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;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
}
作成されたルール:
プライベートメンバー変数がメンバー変数に対して操作する共通get/setメソッドSerializableインタフェースを実現するには必ず公有無参の構造方法がある
2.シーケンス化
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class Serialization {
public static void main(String[] args) {
//
People people = new People(" ", 20, ' ');
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream("F:/001.txt");
//
oos = new ObjectOutputStream(fos);
//
oos.writeObject(people);
//
oos.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
//
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
3.逆シーケンス
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
public class Deserialization {
public static void main(String[] args) {
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream("F:/001.txt");
//
ois = new ObjectInputStream(fis);
//
Object obj = ois.readObject();
if (obj instanceof People) {
People people = (People) obj;
System.out.println(people);
}
} catch (EOFException e) {
// TODO: handle exception
System.out.println(" ");
} 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();
} finally {
//
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}