码迷,mamicode.com
首页 > 其他好文 > 详细

对象流的使用(ObjectInputStream和ObjectOutputStream)

时间:2018-06-04 17:49:04      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:string   nts   class   sys   public   otf   catch   err   使用   

1.在RPC中调用可能会使用对象流的二进制方式来对象的获取和使用

Person对象:

import java.io.Serializable;

public class Person implements Serializable {

	private static final long serialVersionUID = 1L;

	private String name;
	private Long id;

	public Person() {
		super();
	}

	public Person(String name, Long id) {
		super();
		this.name = name;
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

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

}

 2.对象流的测试:

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 ObjectInOutputStreamDemo {
	public static void main(String[] args) {
		outObject();
		readObject();
	}

	private static void readObject() {
		FileInputStream in = null;
		ObjectInputStream ois = null;
		try {
			in = new FileInputStream("person.obj");
			ois = new ObjectInputStream(in);
			Person person = (Person)ois.readObject();
			System.out.println(person);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			if (ois != null) {
				try {
					ois.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	private static void outObject() {
		Person person = new Person("aaa", 10l);
		FileOutputStream out = null;
		ObjectOutputStream oos = null;

		try {
			out = new FileOutputStream("person.obj");
			oos = new ObjectOutputStream(out);
			oos.writeObject(person);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (oos != null) {
				try {
					oos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}

	}

}

 

对象流的使用(ObjectInputStream和ObjectOutputStream)

标签:string   nts   class   sys   public   otf   catch   err   使用   

原文地址:https://www.cnblogs.com/code111/p/9134428.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!