之前写过DataInputStream和DataOutputStream,使用这两个类可以对java基本数据类型进行序列化和反序列化。
本篇再来两个新东西:ObjectInputStream,ObjectOutputStream,这二位不但能对java基本数据类型进行操作,还可以直接干对象,使用起来也更方便。不过,值得注意的是,被干的对象需要实现Serializable接口。
请看下面两个示例
public class Student implements Serializable { private int id; private String name; private long age; private boolean gender; public Student(int id, String name, long age, boolean gender) { this.id = id; this.name = name; this.age = age; this.gender = gender; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getAge() { return age; } public void setAge(long age) { this.age = age; } public boolean isGender() { return gender; } public void setGender(boolean gender) { this.gender = gender; } @Override public String toString() { return "Student{" + "id=" + id + ", name=‘" + name + ‘\‘‘ + ", age=" + age + ", gender=" + gender + ‘}‘; } }
示例1:
@Test public void testObjectStream() throws Exception { String fileName = "E:\\360downloads\\wpcache\\srvsetwp\\student2.txt"; //对象输出流 OutputStream outputStream = new FileOutputStream(fileName); ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream); Student student = new Student(1, "李连杰", 12, true); objectOutputStream.writeObject(student); objectOutputStream.close(); outputStream.close(); //对象输入流 FileInputStream fileInputStream = new FileInputStream(fileName); ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); Student o = (Student) objectInputStream.readObject(); System.out.println(o); //Student{id=1, name=‘李连杰‘, age=12, gender=true} objectInputStream.close(); fileInputStream.close(); }
示例2:
@Test public void testObjectStreamPrimary() throws Exception { String fileName = "E:\\360downloads\\wpcache\\srvsetwp\\student2.txt"; //对象输出流 OutputStream outputStream = new FileOutputStream(fileName); ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream); Student student = new Student(1, "李连杰", 12, true); objectOutputStream.writeInt(student.getId()); objectOutputStream.writeUTF(student.getName()); objectOutputStream.writeLong(student.getAge()); objectOutputStream.writeBoolean(student.isGender()); objectOutputStream.close(); outputStream.close(); //对象输入流 FileInputStream fileInputStream = new FileInputStream(fileName); ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); int id = objectInputStream.readInt(); String name = objectInputStream.readUTF(); long age = objectInputStream.readLong(); boolean gender = objectInputStream.readBoolean(); student = new Student(id, name, age, gender); System.out.println(student); objectInputStream.close(); fileInputStream.close(); }
原文地址:https://www.cnblogs.com/z-qinfeng/p/11794557.html
时间: 2024-10-13 14:46:43