Using Custom Serialization to Transfer Files
This articale is about a little trick that can be used to transfer files, while objects are being serialized. Very often there is a need to transfer file, or files to the remote site. Usual solution is to use FTP either "in process" or as an external call. This is OK, but if the transfered files need some processing, it usually means there will be one FTP call to transfer files, then there will be an RMI (or custom RMI) call to initiate fiel processing.
There is a better way to do this.
Customize Serialization This is easier then you think. To travel across the wire (i,e. participate in the RMI call), object must be serializable. If object is serializable (implements Serializable interface), you can use a little trick. Simply implement 2 methods that will be invoked by JVM during serialization process. These 2 methods have following signatures:
private void writeObject(ObjectOutputStream out) throws IOException;
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException;
Yes, they are private. JVM will invoke them although they are marked as private. Method "writeObject" is invoked when the object is being serialized, and method "readObject" is invoked when object is deserialized.
Implement File Transfer Feature To implement file transfer feature, implement "writeObject" and write all data from the source file to the provided output stream.
Now, on the other side, JVM will invoke "readObject". This is where you need to read the data from the provided input stream and write it to the destination file.
You can download a fully functional object here. Enjoy!
| Reseved for ads |