Java IO 笔记 3 --- 对象流

文章目录

        • 1 Serializable
        • 2 ObjectOutputStream ObjectInputStream
            • 2.1 ObjectOutputStream
            • 2.2 ObjectIntputStream
        • 3 实例代码
        • 4 ObjectOutputStream 用writeObject()输出文本是乱码 问题

如果想整个的存入,读取,自定义的对象,就用到了,操作对象的流 — ObjectOutputStream, ObjectInputStream,被操作的对象,要实现 Serializable(标记接口)

注:流里面的一对,不是两个,是输入和输出相对应

1 Serializable

Serializable 用于给被序列化的类,加入 ID号,用于判断 类和对象,是否是同一个版本

2 ObjectOutputStream ObjectInputStream

2.1 ObjectOutputStream

ObjectOutputStream: 对象的序列化 — 序列化,就是对写入的多个对象,进行排序

我们想把数据,以对象的形式写入到硬盘,但是写入硬盘的数据是文件,怎么转成对象
1 先把数据写入硬盘 new FileOutputStream("obj.object")
2 把写入的数据,变为对象 new ObjectOutputStream()
直接写出来,就是
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("obj.object"));
3 调用 ObjectOutputStream的 writeObject()方法,实现 对象数据的写入
oos.writeObject(new Person("小强",30)); // 注:被序列化的对象 必须实现 Serializable接口
oos.close();

注:在标准开发中,存储对象的文件,不能用 txt 为后缀,其标准后缀名为 .object

2.2 ObjectIntputStream

数据存储起来了,怎么读出来,如果用以前的方法,FileInputStream 能把里面存的数据读出来,但是不能把对象读出来,用 ObjectIntputStream

ObjectInputStream ois = new ObjectInputStream(new FileInputStream("obj.object"));
//对象的反序列化 
Person p = (Person)ois.readObject();
System.out.println(p.getName()+":"+p.getAge());
ois.close();

3 实例代码

Student 类 — 必须实现 Serializable接口

public class Student implements Serializable {
	
	private String name;
	private int age;
	
	public Student(String name,int age){
		super();
		this.name = name;
		this.age = age;
	}
	
	public String toString(){
		return "Student [name=" + name + ", age=" + age + "]";
	}
}

对象流代码

public class ObjectStreamDemo {

	
	public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
		
		ObjectOutputStream oos = new ObjectOutputStream(
				new FileOutputStream("E:"+ File.separator+"test2.object"));

		oos.writeObject(new Student("张三",21));
		oos.writeObject(new Student("lisi",22));
		oos.writeObject(new Student("赵二",23));
		
		
		ObjectInputStream ois = new ObjectInputStream(
				new FileInputStream("E:"+ File.separator+"test2.object"));
		
		for(int i=0;i<3;i++){
			System.out.println(ois.readObject());
		}
	}

}

输出结果

Student [name=张三, age=21]
Student [name=lisi, age=22]
Student [name=赵二, age=23]

4 ObjectOutputStream 用writeObject()输出文本是乱码 问题

找到写的文件,打开,看到里面的内容为

这里写代码片

你可能感兴趣的:(Java,IO)