java中IO流中的对象操作流




java中IO流中的对象操作流




概述

用于从流中读取对象的

ObjectInputStream 称为 反序列化流,利用输入流从文件中读取对象

ObjectOutputStream 称为 序列化,利用输出流向文件中写入对象

特点:用于操作对象。可以将对象写入到文件中,也可以从文件中读取对象




package com.itheima_07;
/*	
 * 对象操作流:可以用于读写任意类型的对象
 * 		ObjectOutputStream
 * 				writeObject 
 * 				ObjectOutputStream(OutputStream out) 
 * 		ObjectInputStream
 * 				readObject
 * 				ObjectInputStream(InputStream in)
 * 
 * 注意:
 * 		使用对象输出流写出对象,只能使用对象输入流来读取对象
 * 		只能将支持 java.io.Serializable 接口的对象写入流中
 * 
 */
public class ObjectOutputStreamDemo2 {
	public static void main(String[] args)  {
		
	}

}



利用序列化流读写对象

package com.itheima_07;

import java.io.Serializable;

public class Student implements Serializable {
	

	/**
	 * 
	 */
	String name;
	int age;

	
	public Student(String name,int age) {
		this.name = name;
		this.age = age;
	}


	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age +"]";
	}
}

package com.itheima_07;
import java.io.EOFException;
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.NotSerializableException: com.itheima_07.Student
 * Serializable:序列号,是一个标识接口,只起标识作用,没有方法
 * 				当一个类的对象需要IO流进行读写的时候,这个类必须实现该接口
 * 
 * Exception in thread "main" java.io.EOFException:当输入过程中意外到达文件或流的末尾时,抛出此异常。
 * 
 */
public class ObjectOutputStreamDemo {
	public static void main(String[] args) throws IOException, ClassNotFoundException  {
		//method();
		//创建对象输入流的对象
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream("a.txt"));
		//读取对象
		/*Object obj = ois.readObject();
		System.out.println(obj);
		
		Object obj2 = ois.readObject();
		System.out.println(obj2);
		
		Object obj3 = ois.readObject();
		System.out.println(obj3);*/
		
		try {
			while(true) {
				Object obj = ois.readObject();
				System.out.println(obj);
			}
		} catch(EOFException e) {
			System.out.println("读到了文件的末尾");
		}
		
		//释放资源
		ois.close();
	}

	private static void method() throws IOException, FileNotFoundException {
		//创建对象输出流的对象
		//FileOutputStream fos = new FileOutputStream("a.txt");
		//ObjectOutputStream oos = new ObjectOutputStream(fos);
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("a.txt"));
		
		//创建学生对象
		Student s = new Student("zhangsan",18);
		Student s2 = new Student("lisi",19);
		//写出学生对象
		oos.writeObject(s);
		oos.writeObject(s2);
		
		//释放资源
		oos.close();
	}

}












评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值