Sanat Pandey
Sanat Pandey

Reputation: 4103

Convert a StringBuffer to a byte Array in Java

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

Upvotes: 34

Views: 59496

Answers (2)

Harshal Waghmare
Harshal Waghmare

Reputation: 1944

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

}

Upvotes: 61

Jeff Grigg
Jeff Grigg

Reputation: 1014

I say we have an answer, from Greg:

String.valueOf(stringBuffer).getBytes()

Upvotes: 36

Related Questions