java中IO流中的对象操作流(2)——解决对象输入流读取对象出现异常的问题

来源:互联网 发布:淘宝拍摄相机推荐 编辑:程序博客网 时间:2024/05/16 01:12



解决对象输入流读取对象出现异常的问题


package com.itheima_07;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.util.ArrayList;/* * 解决对象输入流读取对象出现异常的问题 *  */public class ObjectOutputStreamDemo3 {public static void main(String[] args) throws IOException, ClassNotFoundException   {//method();//创建对象输入流的对象ObjectInputStream ois = new ObjectInputStream(new FileInputStream("b.txt"));//读取数据Object obj = ois.readObject(); //System.out.println(obj);//向下转型,获取具体的子类对象ArrayList<Student> list = (ArrayList<Student>) obj;for (Student student : list) {System.out.println(student);}//释放资源ois.close();}private static void method() throws IOException, FileNotFoundException {//创建对象输出流的对象ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("b.txt"));//创建集合对象ArrayList<Student> list = new ArrayList<Student>();//添加学生对象list.add(new Student("wangwu",30));list.add(new Student("zhaoliu",28));//写出集合对象oos.writeObject(list);//释放资源oos.close();}}




解决读写对象版本不一致问题

package com.itheima_07;import java.io.Serializable;public class Student implements Serializable {/** *  */private static final long serialVersionUID = 6361890890437825953L;String name;int age;String gender;public Student(String name,int age) {this.name = name;this.age = age;}@Overridepublic String toString() {return "Student [name=" + name + ", age=" + age + ", gender=" + gender + "]";} }package com.itheima_07;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;/* * 解决对实现序列化接口出现的黄色警告问题 * Exception in thread "main" java.io.InvalidClassException * 当 Serialization 运行时检测到某个类具有以下问题之一时,抛出此异常。 该类的序列版本号与从流中读取的类描述符的版本号不匹配 该类包含未知数据类型 该类没有可访问的无参数构造方法  *  */public class ObjectOutputStreamDemo4 {public static void main(String[] args) throws IOException, ClassNotFoundException  {//method();method2();}//读取学生对象private static void method2() throws IOException, FileNotFoundException, ClassNotFoundException {//创建对象输入流的对象ObjectInputStream ois = new ObjectInputStream(new FileInputStream("c.txt"));//读取对象Object obj = ois.readObject();System.out.println(obj);//释放资源ois.close();}//写出学生对象private static void method() throws IOException, FileNotFoundException {//创建对象输出流的对象ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("c.txt"));//创建的学生对象Student s = new Student("qianqi",28);//写出学生对象oos.writeObject(s);//释放资源oos.close();}}






阅读全文
0 0