« Visualizing Mailing Lists | Main | How Do You Like Your Documentation? »
January 15, 2004
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?
Posted by cantrell at January 15, 2004 12:03 AM | References
Comments
<cfset byteClass = createObject("java","java.lang.Byte").init(0).getClass() />
<cfset byteArray = createObject("java","java.lang.reflect.Array").newInstance(byteClass,42) />
Posted by: Sean Corfield at January 15, 2004 01:14 AM
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>
Posted by: Christian Cantrell at January 15, 2004 05:05 PM
Thee best bloggg
Posted by: Meban at February 20, 2004 07:34 AM
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 /]
Posted by: Barney at August 31, 2005 02:41 PM