判断对象流已经读取到末尾方法
转载:https://blog.csdn.net/wolfcode_cn/article/details/80701035
判断对象流已经读取到末尾方法
1 怎么判断对象流已经读取到末尾 2 如果读取超过了则会抛出异常java.io.EOFException 3 方法一 4 在存入对象的时候使用集合的方式来存储对象,这样在获取时就只需要获取集合,然后遍历集合即可. 5 @Test 6 public void testObjectOutputStream() throws Exception { 7 ObjectOutputStream ojbOs = new ObjectOutputStream(new FileOutputStream(new File("user.obj"))); 8 // 用集合存入对象 9 List<Student> list = new ArrayList<Student>(); 10 list.add(new Student("willie", 18)); 11 list.add(new Student("xiaoming", 18)); 12 // 写入对象 13 ojbOs.writeObject(list); 14 ojbOs.close(); 15 } 16 17 @Test 18 public void testObjectInputStream() throws Exception { 19 ObjectInputStream ojbIs = new ObjectInputStream(new FileInputStream(new File("user.obj"))); 20 // 读取出集合对象 21 List<Student> list = (List<Student>)ojbIs.readObject(); 22 // 编辑集合 23 list.forEach(System.out::println); 24 ojbIs.close(); 25 } 26 这种是将本来的多个对象转化为一个集合对象,再从集合对象中去获取数据 27 28 方式二 29 方式一的方式可以说是比较好的解决方案,如果不想转为集合对象也可以在存入对象前或者后面加一个标志, 30 可以在第一位置加一个int类型的值来记录存入的对象个数,也可以在最后加入一个null来做结束标识. 31 看到这里是不是已经知道怎么解决,如果还不知道!没关系,上代码. 32 33 @Test 34 public void testObjectOutputStream2() throws Exception { 35 ObjectOutputStream ojbOs = new ObjectOutputStream(new FileOutputStream(new File("student.obj"))); 36 // 写入对象 37 ojbOs.writeObject(new Student("willie", 18)); 38 ojbOs.writeObject(new Student("xiaoming", 18)); 39 // 写入一个 null 对象作为结束标识 40 ojbOs.writeObject(null); 41 ojbOs.close(); 42 } 43 44 @Test 45 public void testObjectInputStream2() throws Exception { 46 ObjectInputStream ojbIs = new ObjectInputStream(new FileInputStream(new File("student.obj"))); 47 // 读取出集合对象 48 Object obj = null; 49 // 遍历对象,直到遇到null 50 while((obj = ojbIs.readObject()) != null){ 51 Student stu =(Student)obj; 52 System.out.println(stu); 53 } 54 55 ojbIs.close(); 56 } 57 方式三 58 使用异常处理方式,这个很简单,直接处理 EOFException 就行了,当遇到EOFException 时表示已经读到末尾了. 59 60 public void testObjectInputStream3() throws Exception { 61 ObjectInputStream ojbIs = new ObjectInputStream(new FileInputStream(new File("student.obj"))); 62 List<Student> list = new ArrayList<>(); 63 try { 64 // 读取对象 65 while(true){ 66 Student stu = (Student)ojbIs.readObject(); 67 list.add(stu); 68 } 69 } catch (Exception e) { 70 // 读取结束后的操作 71 System.out.println(list); 72 } 73 ojbIs.close();