欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ObjectInputStream和ObjectOutputStream

程序员文章站 2022-04-03 19:54:04
...

ObjectInputStream和ObjectOutputStream的简单示例

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Main {
	public static void main(String[] args) throws Exception {
		String fileName = "t.tmp"; 
		FileOutputStream fos = new FileOutputStream(fileName); 
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		oos.writeObject(new Point(1, 1)); 
		oos.writeObject(new Point(2, 2));
		fos.close(); 
		oos.close(); 
		
		FileInputStream fis = new FileInputStream(fileName); 
		ObjectInputStream ois = new ObjectInputStream(fis);
		while(true){
			Point tp = null; 
			try {
				tp = (Point)ois.readObject();
			} catch (Exception e) {
				break;
			}
			System.out.println(tp.getx() + "  " + tp.gety());
		}
		System.out.println("over");
		fis.close();
		ois.close(); 
	}
}
class Point implements Serializable{
	private static final long serialVersionUID = 1127043316960106769L;
	private int x, y; 
	Point(int x, int y){
		this.x = x; 
		this.y = y; 
	}
	
	public int getx(){
		return x; 
	}	
	public int gety(){
		return y; 
	}
}