`
liuwei1981
  • 浏览: 754932 次
  • 性别: Icon_minigender_1
  • 来自: 太原
博客专栏
F8258633-f7e0-30b8-bd3a-a0836a5f4de5
Java编程Step-by...
浏览量:156792
社区版块
存档分类
最新评论

Java对象序列化

阅读更多

   将对象转化为一个流对象:

public InputStream setObjectAsStream(Object obj) {
		InputStream ret = null;
		ByteArrayOutputStream baos = null;
		ObjectOutputStream ous = null;

		if (obj == null) {
			return ret;
		}
		try {
				baos = new ByteArrayOutputStream();
				ous = new ObjectOutputStream(baos);
				ous.writeObject(order);

				ret = getInputStreamFromBytes(baos.toByteArray());

			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (baos != null) {
					baos.close();
				}
				if (ous != null) {
					ous.close();
				}
			} catch (Exception e) {
			}
		}
		return ret;
	}

 

public static InputStream getInputStreamFromBytes(byte[] bytes) {
		InputStream ret = null;
		try {
			if (bytes == null || bytes.length <= 0) {
				return ret;
			}
			ret = new ByteArrayInputStream(bytes);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}

 

 

将对象写入流

 

 

OutputStream os = con.getOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(os);
			oos.writeObject(obj);
			oos.flush();
			oos.close();

//con 为Soket链接

 

从流中读出对象

 

 

public Object getObject (InputStream is) {
		Object ret = null;

		ObjectInputStream ois = null;
		try {
			if (is != null) {
				ois = new ObjectInputStream(is);
				ret = (Object ) ois.readObject();
			}
		} catch (Exception e) {
		} finally {
			try {
				if (ois != null) {
					ois.close();
				}
			} catch (Exception e) {
			}
		}
		return ret;
	}

 

  Objec对象需要 implements implements java.io.Serializable。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics