Byte Arrays and ColdFusion

I’m looking for ways to dynamically create byte arrays of indeterminate length in ColdFusion. I have tried this:


sb = createObject("java", "java.lang.StringBuffer");
sb.init(someLength);
byteArray = sb.toString().getBytes();

// and this:

baos = createObject("java", "java.io.ByteArrayOutputStream");
baos.init(someLength);
byteArray = boas.toByteArray();

… but both return byte arrays of 0 length rather than someLength. The only technique I have found that works is this:


function getByteArray(someLength)
{
sb = createObject("java", "java.lang.StringBuffer");
for (i = 0; i lt someLength; i = i + 1)
{
sb.append("_");
}
return sb.toString().getBytes();
}

This works, but as you might expect, it’s not the most efficient technique. Any other ideas?

4 Responses to Byte Arrays and ColdFusion

  1. <cfset byteClass = createObject(“java”,”java.lang.Byte”).init(0).getClass() /><cfset byteArray = createObject(“java”,”java.lang.reflect.Array”).newInstance(byteClass,42) />

  2. Thanks, Sean. That got me on the right track. That returns a Byte array (object), and I need a byte array (primitive). This is what I settled on:<cffunction name="getByteArray" access="private" returnType="any" output="no"><cfargument name="size" type="numeric" required="true"/><cfset var emptyByteArray = createObject("java", "java.io.ByteArrayOutputStream").init().toByteArray()/><cfset var byteClass = emptyByteArray.getClass().getComponentType()/><cfset var byteArray = createObject("java","java.lang.reflect.Array").newInstance(byteClass, arguments.size)/><cfreturn byteArray/></cffunction>

  3. Meban says:

    Thee best bloggg

  4. Barney says:

    This is way late to the discussion, but if you want the class of a primitive type, the wrapper classes provide easier access.[cfset byteClass = createObject(“java”, “java.lang.Byte”).TYPE /]