public class TestObjectStream {
public static void main(String[] args) {
T t = new T();
t.name = "jay chou";
FileOutputStream fos = null;
ObjectOutputStream oos = null;
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fos= new FileOutputStream("D:\\bak\\test.dat");
oos = new ObjectOutputStream(fos);
oos.writeObject(t);
oos.writeDouble(0.1);
oos.flush();//不加这一句,有可能出现异常java.io.EOFException
fis = new FileInputStream("D:\\bak\\test.dat");
ois = new ObjectInputStream(fis);
T tt = (T)ois.readObject();
double d = ois.readDouble();
System.out.println(tt);
System.out.println(d);
} catch (IOException e) {
e.printStackTrace();
}catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
ois.close();
fis.close();
oos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class T implements Serializable {//必须实现该接口,才可使用户自定义类可以序列化
String name = "jay";
transient int i = 7;
long t = 10L;
double d = Math.random();
char c = 'a';
public String toString() {
return ("name " + name + " i: " + i + " t:" + t + " d: " + d + " c: " + c);
}
}
/*
D:\java\io>javac TestObjectStream.java
D:\java\io>java TestObjectStream
name jay chou i: 7 t:10 d: 0.7328874131779102 c: a
0.1