对象流的使用(ObjectInputStream和ObjectOutputStream)

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();
				}
			}

		}

	}

}

猜你喜欢

转载自www.cnblogs.com/code111/p/9134428.html