性能提高技巧之一:使用ByteArrayInputStream或ByteArrayOnputStream

banq 02-12-10

和sokcet的结合

DataInputStream in = new DataInputStream ( socket.getInputStream ( ) );

byte[ ] barray = new Byte [ sizeNeeded ];

in.read ( barray );

ByteArrayInputStream bais = new ByteArrayInputStream ( barray );


对象可以通过数据包传送:

Writing Object to stream
-------------------------
//create ByteArrayOutputStream
ByteArrayOutputStream baos = new ByteArrayOutputStream();

//create ObjectOutputStream to write objects
ObjectOutputStream oos = new ObjectOutputStream(baos);

//write the object to the stream
oos.writeObject(obj);

//flush the stream
oos.flush();

Reading Object from stream
-------------------------
//byte array input stream
ByteArrayInputStream bais = new ByteArrayInputStream(data);

//object input stream
ObjectInputStream ois = new ObjectInputStream(bais);

//object from the stream
ois.readObject();

1
banq
2002-12-10 10:20

我们一般读取socket是将数据封装在byte array, 因为很多操作是对array操作,array操作是麻烦而且需要小心。使用ByteArrayInputStream后,可以达到一种将数组转换的目的

banq
2002-12-10 11:28

用于对象序列化,将对象保存在数据库中:

This is what I use to serialize and deserialize objects to a DBMS:

/**
* Converts a serializable object to a byte array.
*/
private byte[] objectToBytes(Object object)
throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(baos);
os.writeObject(object);
return baos.toByteArray();
}

/**
* Converts a byte array to a serializable object.
*/
private Object bytesToObject(byte[] bytes)
throws IOException, ClassNotFoundException
{
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream is = new ObjectInputStream(bais);
return is.readObject();
}

then,
byte[] bytes = objectToBytes(myObject);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
pstmt.setBinaryStream(1, bais, bytes.length);
pstmt.executeUpdate();