Convert a StringBuffer to a byte Array in Java

Sanat Pandey picture Sanat Pandey · Nov 4, 2011 · Viewed 48k times · Source

How might I, in Java, convert a StringBuffer to a byte array?

Answer

Harshal Waghmare picture Harshal Waghmare · Mar 11, 2013

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

}