Object I/O

如何在二进制IO中读写对象?
使用 ObjectInputStream/ObjiectOutputStream 类,是Inputstream和Outputstream的子类,可以读写原始数据类型也可以读写对象
在这里插入图片描述
在这里插入图片描述
构造方法

	ObjectOutputStream os=new ObjectOutputStream(OutputStream out);
	ObjectInputStream os=new ObjectInputStream(InputStream in);

使用

public static void main(String[]args)  {
		String path="D:\\text.dat";
		File test=new File("D:\\test.txt");
		try {
			ObjectOutputStream os=new ObjectOutputStream(new FileOutputStream(path));
			ObjectInputStream is=new ObjectInputStream(new FileInputStream(path));
			os.writeObject(new java.util.Date());//写入当前时间的Date对象
			System.out.println("object read:"+is.readObject());
			//可能会抛出 ClassNotFoundException
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

对于对象的限制:
只有实现了Serializable 接口的类才能读写.
Serializable接口没有任何方法,只是一个标记.

posted @ 2019-08-03 10:37  少年留不住  阅读(367)  评论(0编辑  收藏  举报