对象流【ObjectinputStream,ObjectinputStream】

1、测试类 

package com.wyq.print;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class TestObjectOutputStream {
	public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
		/**
		 * 写入
		 */
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("d:\\a.txt"));
		oos.writeObject(new String("JLFDSJSLKDJFALKSD"));
		oos.writeInt(12);
		oos.writeBoolean(false);
//		oos.close();
		Person per =new Person("李四",18);
		System.out.println(per);
		oos.writeObject(per);
		oos.writeObject(new Person("张三", 12));
		oos.write('a');
		oos.flush();
		/**
		 * 读取
		 */
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d://a.txt"));
		System.out.println(ois.readObject());
		System.out.println(ois.readInt());
		System.out.println(ois.readBoolean());
		System.out.println(ois.read());
		Person p = (Person) ois.readObject();
		System.out.println(p.getName()+"\t"+p.getAge());
		ois.close();
	}

}

2、自己编写类

package com.wyq.print;

import java.io.Serializable;

public class Person implements Serializable{
	private String name;
	private int age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	public Person() {
		super();
	}

}

3、总结:

1)自己编写的类一定要实现Serializable接口,否则不能往文件中写入数据

2)读取与写入的类型应该先相同,这种情况下更少出错

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值