IO读取是相对严格的,一般通过相应的outputstream写入的数值,必须通过相对应的InputStream来读取,否则数值是不对的,也就是显示是乱码或者错误的。譬如我们用ObjectOutputStream写入一段数据到一个test.txt的文件中,写入的数值是二进制的,用记事本打开可能看不出什么名堂,我们可以利用UtrlEdit查看对应的二进制代码,其实呢,还是没不懂啥意思,哈哈,因此我们必须用ObjectInputStream来读取test.txt中的数据,否则就会出错。
下面是一段演示代码: Serializatiom.java
import java.io.*;

/** *//**
* 序列化对象输入输出
*/
public class Serialization 
...{
public static void main(String[] args) throws IOException,ClassNotFoundException
...{
Student stu = new Student(19,"MiLdo",24,"中国特警队"); //Student的构函是带参数的。
FileOutputStream fos = new FileOutputStream("d:\java\Serialization.txt");
ObjectOutputStream oop = new ObjectOutputStream(fos);
try
...{
oop.writeObject(stu);
oop.close();
}
catch(IOException e)
...{
System.out.println(e.getMessage());
}
stu = null;
FileInputStream fis = new FileInputStream("d:\java\Serialization.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
try
...{
stu = (Student)ois.readObject(); //时时不忘类型转换。
ois.close(); //时时不忘关闭流对象
}
catch(IOException e)
...{
System.out.println(e.getMessage());
}
System.out.println("student id = "+stu.id);
System.out.println("student name = "+ stu.name);
System.out.println("student age = "+ stu.age);
System.out.println("student department = "+stu.department);
}
}
class Student implements Serializable
...{
int id;
String name;
int age;
String department;
public Student(int id,String name,int age,String department)
...{
this.id = id;
this.name = name;
this.age = age;
this.department = department;
}
}