IO流之对象专属流
IO流之对象专属流
单个对象
以下代码把一个Java对象从内存中写入到硬盘,再读回到内存:
package com.javalearn.io.ObjectIO;
import java.io.*;
public class TestForObjIO {
public static void main(String[] args) throws Exception{
Student s = new Student(1111,"cxf");
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("file1"));
oos.writeObject(s); // 序列化
oos.flush();
oos.close();
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("file1"));
Object obj = objectInputStream.readObject(); // 反序列化
System.out.println(obj); // 自动执行toString方法
objectInputStream.close();
}
}
class Student implements Serializable { // 实现Serializable接口,才能序列化
private int no; // 若加上transient关键字,则此属性不参与序列化,反序列化时显示null
private String name;
public Student() {
}
public Student(int no,String name) {
this.no = no;
this.name = name;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student{" +
"no=" + no +
", name='" + name + '\'' +
'}';
}
}
输出结果:
Student{no=1111, name='cxf'}
多个对象
以下代码进行多个对象的IO:
package com.javalearn.io.objIOset;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class TestForMultiObj {
public static void main(String[] args) throws Exception{
List<User> userList = new ArrayList<>(); // 用集合装载对象
userList.add(new User(1,"cxf"));
userList.add(new User(2,"smf"));
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("file1"));
oos.writeObject(userList); // 把集合序列化
oos.flush();
oos.close();
ObjectInputStream ois =new ObjectInputStream(new FileInputStream("file1"));
List<User> userList1 = (List<User>) ois.readObject(); // 反序列化
for(User user:userList1) {
System.out.println(user);
}
ois.close();
}
}
class User implements Serializable {
private int no;
private String name;
public User() {
}
public User(int no, String name) {
this.no = no;
this.name = name;
}
@Override
public String toString() {
return "User{" +
"no=" + no +
", name='" + name + '\'' +
'}';
}
}
输出结果:
User{no=1, name='cxf'}
User{no=2, name='smf'}