IO Serializableのシーケンス化と逆シーケンス化、およびカスタムシーケンス化
package IO;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Serializable1
{
public static void main(String[] args) throws Exception
{
Person2 p1 = new Person2(21,"zhangsan",4.33);
Person2 p2 = new Person2(232,"zhangan",66.33);
Person2 p3 = new Person2(22,"zhanan",6.33);
FileOutputStream fos = new FileOutputStream("pp.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(p1);
oos.writeObject(p2);
oos.writeObject(p3);
oos.close();
System.out.println("--------------");
FileInputStream is = new FileInputStream("pp.txt");
ObjectInputStream ois = new ObjectInputStream(is);
Person2 p= null;
for(int i = 0; i <3 ; i++)
{
p = (Person2)ois.readObject();
System.out.println(p.age + " " + p.name + " "+ p.height);
}
ois.close();
}
}
class Person2 implements Serializable
{
int age;
String name;
double height;
public Person2(int age,String name,double height)
{
this.age = age;
this.name = name;
this.height = height;
}
private void writeObject(java.io.ObjectOutputStream ou)throws IOException // serializable
{
System.out.println("write object");
ou.writeInt(age);
ou.writeUTF(name);
}
private void readObject(java.io.ObjectInputStream in)throws IOException,ClassNotFoundException
{
age = in.readInt();
name = in.readUTF();
System.out.println("read Object");
}
}
java.io.ObjectOutputStream. java.io.ObjectInputStreamカスタムシーケンス化方法