34

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

2
  • 9
    can you just do String.valueOf(stringBuffer).getBytes()? Commented Nov 4, 2011 at 5:50
  • 9
    Make sure to specify the encoding with 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. Commented Nov 4, 2011 at 6:03

2 Answers 2

61

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

}
Sign up to request clarification or add additional context in comments.

Comments

36

I say we have an answer, from Greg:

String.valueOf(stringBuffer).getBytes()

3 Comments

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.
@chendu what is your recommended suolution?
@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;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.