日期:2014-05-20  浏览次数:20831 次

ObjectInputStream的readInt()方法问题
练习序列化和反序列化问题,自己写了以下代码 

import java.io.*;
import java.util.Date;
class Student implements Serializable
{
  private String name;
  private int age;
  private char sex;
   
  public Student(String name,int age,char sex)
  {
  this.name=name;
  this.age=age;
  this.sex=sex;
  }
  
  public String toString()
  {
  return "姓名:"+name+" 年龄"+age+" 性别"+sex;
  }


}
public class ObjectSerTest
{
public static void main(String args[])
{
try{

FileOutputStream fos=new FileOutputStream("test.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);

Student s1=new Student("张三",20,'m');
Student s2=new Student("王五",21,'f');

String str="hello";
Date date=new Date();
Integer i=10;

oos.writeObject(s1);
oos.writeObject(s2);
oos.writeObject(str);
oos.writeObject(date);
oos.writeObject(i);  

  oos.writeInt(100);

FileInputStream fis=new FileInputStream("test.txt");
ObjectInputStream ois=new ObjectInputStream(fis);

Student s3=(Student)ois.readObject();
Student s4=(Student)ois.readObject();
String str1=(String)ois.readObject();
Date d1=(Date)ois.readObject();
Integer j=(Integer)ois.readObject();
int k=ois.readInt();
 
System.out.println(s3);
System.out.println(s4);
System.out.println(str1);
System.out.println(d1);
System.out.println(j);  
System.out.println(k);
 

ois.close();
fis.close();
oos.close();
fos.close();
}
catch(IOException e)
{
e.printStackTrace();
}
catch(ClassNotFoundException e1)
{
e1.printStackTrace();
}
}
}

以上红色代码去掉,程序能正常出结果,但是红色代码加上运行后,报io.EOFException,难道不能用readInt()方法直接读取
基本数据类型吗??请问原因是什么?

------解决方案--------------------
writeInt(100) 这个不是序列化的写法呀。。你这个又没写到text文件里 如何读取?只有writeObject的
------解决方案--------------------
看了EOFException异常的说明你就知道为什么要先关闭OOS了
Signals that an end of file or end of stream has been reached unexpectedly during input. 

This exception is mainly used by data input streams to signal end of stream. Note that many other input operations return a special value on end of stream rather than throwing an exception. 


------解决方案--------------------
writeObject,只要调用,系统会自己就去将这个对象写入流并存入文件。

readInt这种写入基本数据的则不是这样
基本数据以块数据记录的形式写入 ObjectOutputStream 中。块数据记录由头部和数据组成。块数据部分包括标记和跟在部分后面的字节数。连续的基本写入数据被合并在一个块数据记录中。块数据记录的分块因子为 1024 字节。每个块数据记录都将填满 1024 字节,才会被写入。
简单的说,只写一个100,是不够1024字节的,所以要手动调用close()才会写入。

另外,还有一种情况,就是在终止块数据模式时也可以写入基本数据。当调用writeObject()是可以终止现在块数据记录的。所以楼主把oos.writeInt(100);放到任一个oos.writeObject()之前,也是可以的。(当然readInt()的位置也相应调一下)