How might I, in Java, convert a StringBuffer to a byte array?
2 Answers
A better alternate would be stringBuffer.toString().getBytes()
Better because String.valueOf(stringBuffer) in turn calls stringBuffer.toString(). Directly calling stringBuffer.toString().getBytes() would save you one function call and an equals comparison with null.
Here's the java.lang.String implementation of valueOf method:
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
Comments
I say we have an answer, from Greg:
String.valueOf(stringBuffer).getBytes()
3 Comments
chendu
this will first replicate the buffer. If the input stringBuffer is 1MB size then you will be creating another 1MB object and then converting it to bytes. Not a good solution.
Eric
@chendu what is your recommended suolution?
chendu
@Eric I dont have a clean solution. May be we shouldnt use string buffer. The closest dirty solution is to access the StringBuffer variable:
private transient char[] toStringCache; via reflections and copy it into String class variable private final char[] value;
getBytes... "Encodes this String into a sequence of bytes using the platform's default charset..." This is one of the silly areas where they didn't just pick a universal default.