开发者

get String length in StringWriter?

开发者 https://www.devze.com 2023-01-16 13:49 出处:网络
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:

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();
?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消