« 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

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 1: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 5:05 PM

Thee best bloggg

Posted by: Meban at February 20, 2004 7: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 2:41 PM




Remember Me?

(you may use HTML tags for style)

Copyright © 2009 Adobe Systems Incorporated. All rights reserved.
Use of this website signifies your agreement to the Terms of Use and Online Privacy Policy (updated 07-14-2009).