ObjectInputStream怎么判断是否读到末尾

ObjectInputStream无论是读对象,还是记取int等java的基本数据类型,在判结束时,绝对既不是-1,也不是什么null。

若文件中有若干个int的数,你用DataInputStream中的readint()去读,何时判读到结尾?绝对既不是-1,也不是什么null

同样道理:若文件中有若于个Object对象,你用ObjectInputStream中的readObject()去读,何时判读到结尾?绝对既不是-1,也不是什么null

方法之一:(常用的方法)将若干个对象(数量不定)都装入一个容器中(如:ArrayList之类),然后将容器这一个对象写入就行了。读取时,只要读取一个对象(即容器对象)就行了

例如:

 1  public ArrayList<Person> readPerson(String pathName){
 2         ArrayList<Person> list = null;
 3         FileInputStream fis;
 4         ObjectInputStream ois;
 5         try {
 6             fis = new FileInputStream(pathName);
 7             ois = new ObjectInputStream(fis);
 8             
 9             list = (ArrayList<Person>) ois.readObject(); 
10             
11             System.out.println("加载人员库完成!");
12             fis.close();
13             ois.close();
14         } catch (FileNotFoundException e) {
15             e.printStackTrace();
16         } catch (IOException e) {
17             e.printStackTrace();
18         } catch (ClassNotFoundException e) {
19             e.printStackTrace();
20         }finally{
21             return list;
22         }
23     }

用ArrayList来包裹Person,直接读入一个ArrayList对象。

方法之二:使用EOFException来判断结束。

 try{
      while(true)
      {
            Object o=ois.radObject();
            //处理已读出的对象o;
       }
 }catch(EOFxception e){
 //已从流中读完。
 }
finallly{
流的关闭。
}

原文地址:https://www.cnblogs.com/mo-xue/p/5778178.html