tags:

views:

53

answers:

2

I'm using JAXB, I need to know the length of generated XML, so I marshal the content to StringWriter, so which way is better to get the length:

aStringWriter.getBuffer().length();
 or

aStringWriter.toString().length();
?

+2  A: 

EDIT: Calling toString() will always create a new string... although it won't need to copy the actual character data, just create a new string referring to the current char[] with the current length and count. Calling getBuffer().length() doesn't need to create any extra objects though, so it's slightly more efficient.

What are you doing with the output though? Aren't you converting it to a string anyway?

Note that the length here will always be the length in characters though, so it won't be suitable for something like the Content-Length header of an HTTP responses, which needs the value in bytes (i.e. after encoding).

EDIT: Okay, if you want the byte count instead, I suggest you create a ByteArrayOutputStream, and either pass that directly to JAXB if you can (I've forgotten what the API looks like) or create an OutputStreamWriter around it. That way you can get the binary length from the ByteArrayOutputStream instead.

Jon Skeet
I'm adding the content to HTTP body, and yes actually, I need to set the Content-Length Header
mabuzer
@mabuzer: Edited.
Jon Skeet
A: 

I do this

Charset UTF8Charset = Charset.forName("UTF8");
String output = stringWriter.toString();
response.setContentType("application/xml");
response.setContentLength(output.getBytes(UTF8Charset).length);
PrintWriter out = response.getWriter();
out.print(output);

Works perfect for all UTF-8 strings.

Ashish Patil