Java对象序列化

本文介绍如何将Java对象转换为字节流以及从字节流中读取对象的方法,并提供了具体的实现代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值