本文共 2735 字,大约阅读时间需要 9 分钟。
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); //向下转型,获取具体的子类对象 ArrayListlist = (ArrayList ) 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 list = new ArrayList (); //添加学生对象 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; } @Override public 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(); }}
转载地址:http://mnjqb.baihongyu.com/