Wednesday, January 14, 2009

Serializing Inputstreams

Obviously input streams can not be serialized, nevertheless I recently had a similar problem.

I had to read the contents of a file (some random bytes) and call a JEE remote method with this bytes as parameter.

Just calling the remote method with the FileInputStream as parameter is what you do without remoting but what to do in this case?

As I was lucky and the files are small I used the following trivial solution where I just read the file into a byte array call the method with this byte array.

FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[(int) file.length()];

int read = fis.read(buffer);

if (read != file.length())
{
throw new IOException("Error reading file. Only read " +
read + " bytes instead of "+ file.length());
}

sessionBean.remoteMethod(buffer);

This only works for small files that fit into a byte array. And I still look for a more general purpose solution. But for now it works.
Post a Comment