Saturday, August 15, 2009

Jython - Convert File to Byte Array


I've recently started developing with Jython and I love the language. the combination of Python's dynamic features with Java is extremely powerful. If you are not familiar with Python or Jython, be sure to check the above links. As an Action Script veteran, I have to admit that Python makes me miss the early days of AS, when the language was dynamic and weakly typed.

The following is an example of a typical web client task, a conversion of a local file to a Byte array, such a conversion is common when sending a local file from the client to a Java server, using SOAP Web Services or other integration layer. Here is an example of a file to Byte array conversion in Jython, it's a Jython version of a simple java code I've found here:

from java.lang import Byte
from java.io import FileInputStream
from java.io import File
import jarray

def getByteArray(self,fileUrl):
file = File(fileUrl);
inputStream = FileInputStream(file)
length = file.length()
bytes = jarray.zeros(length, 'b')
#Read in the bytes
offset = 0
numRead = 0
while offset<length:
if numRead>= 0:
print numRead
numRead=inputStream.read(bytes, offset, length-offset)
offset = offset + numRead
return bytes

As you can see, I had to use the jarray Jython module in this code. Jarray provides a much needed API that is missing from Jython's core modules. It exposes two methods which allow you to construct Typed Arrays and\or determine the array length on creation. The following are the two jarray methods:

array(sequence, type):
Creates an array of a specific type with values from the sequence; the array is the same size as the sequence

zeros(length, type):
Creates an empty array the length of the length parameter

The follwoing line in my code:

bytes = jarray.zeros(length, 'b')

Is the jarray, Jython implementation of the following java code:

byte[] bytes = new byte[(int)length];

2 comments:

Eli said...

Jython is fun to work with!
I am glad I am not the only one who's enjoying its flexibility and extendability.

Go Lior!

Ashwin Kumar said...

thank you... you saved my day :)