Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a StringBuffer to a byte Array in Java

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

like image 256
Sanat Pandey Avatar asked Nov 04 '11 05:11

Sanat Pandey


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();  } 
like image 169
Harshal Waghmare Avatar answered Sep 19 '22 00:09

Harshal Waghmare


I say we have an answer, from Greg:

String.valueOf(stringBuffer).getBytes() 
like image 43
Jeff Grigg Avatar answered Sep 23 '22 00:09

Jeff Grigg