Forums Register Login

Serialize object with nio

+Pie Number of slices to send: Send
I notice that oos.writeObject(aObject) is slow. What should I do to get better performance? What I want to do is to serialize an object to a byte array and store this byte array to a table. I know the java.nio package helps to increase i/o performance, but I could not find any sample code doing this. How do I replace stream with channel?
+Pie Number of slices to send: Send
Well,as you may know, you use Buffers to work with NIO channels. You can get an object into a byte array by using an ObjectOutputStream wrapped around a ByteArrayOutputStream. After you are done writing the object, you can get the array from the ByteArrayOutputStream by calling its toByteArray() method which returns a byte array. Now that you have the object in a byte array, you need to get it into a Buffer. The best choice for this is the ByteBuffer class since it is implemented using a byte array internaly. You can obtain a ByteBUffer object that contains this data by calling the static method wrap(byte[]) and passing the byte array you had. You can now send the data through the channel by calling it's write(Buffer) method and passing the buffer. In order to retrieve the data using NIO, you would do the exact opposite using the input stream complements to the output streams you used.

Done using NIO SocketChannels:
* Note, not accounting for exceptions. Catch them yourself *

+Pie Number of slices to send: Send
sc = (SocketChannel) channel;
ByteArrayOutputStream baos = new ByteArrayOutputStream(); //make a BAOS streamObjectOutputStream oos = new ObjectOutputStream(baos); // wrap and OOS around the stream
oos.write(new Integer(5)); // write an object to the stream
byte[] objData = baos.toByteArray(); // get the byte array


1. Do I need to create a socket to do this? I don't need a socket because I just want to get a byte array.
2. The invocation of oss.write(...) is pretty slow. Is there any way I can make it run faster?
3. baos.toByteArray() is not an evil method since it returns a deep copy of the byte array.
Whatever. Here's a tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 3862 times.
Similar Threads
byte[] to blob
java.io. NotSerializableException: java.io.ByteArrayOutputStream
How to transport 2 dimension array of integer using byte array.
How to clone Value Objects
Serializing a ByteArrayOutputStream
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 03:54:45.