星期一, 二月 23, 2004

Java Serializable 例程

// write.java
//http://java.sun.com/developer/TechTips/1998/tt0217.html
import java.io.*;
public class write {
public static void main(String args[])
{
try {
FileOutputStream fos =
new FileOutputStream("file.out");
ObjectOutputStream oos =
new ObjectOutputStream(fos);
oos.writeObject(new Test("testing", 37));
oos.flush();
fos.close();
}
catch (Throwable e) {
System.err.println(e);
}
}
}

// read.java
import java.io.*;
public class read {
public static void main(String args[])
{
Test testobj = null;
try {
FileInputStream fis =
new FileInputStream("file.out");
ObjectInputStream ois =
new ObjectInputStream(fis);
testobj = (Test)ois.readObject();
fis.close();
}
catch (Throwable e) {
System.err.println(e);
}
System.out.println(testobj.str);
System.out.println(testobj.ivalue);
}
}

// Test.java
public class Test implements java.io.Serializable {
public String str;
public transient int ivalue;
public Test(String s, int i)
{
str = s;
ivalue = i;
}
}