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。

你可能感兴趣的:(java,OS)