Convert a StringBuffer to a byte Array in Java
Asked Answered
U

2

34

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

Uredium answered 4/11, 2011 at 5:41 Comment(2)
can you just do String.valueOf(stringBuffer).getBytes()?Crenel
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.Bryant
E
36

I say we have an answer, from Greg:

String.valueOf(stringBuffer).getBytes()
Emanuele answered 4/11, 2011 at 12:53 Comment(3)
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.Gymkhana
@Gymkhana what is your recommended suolution?Hama
@Hama 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;Gymkhana
O
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();

}
Overwhelming answered 11/3, 2013 at 8:37 Comment(0)
E
36

I say we have an answer, from Greg:

String.valueOf(stringBuffer).getBytes()
Emanuele answered 4/11, 2011 at 12:53 Comment(3)
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.Gymkhana
@Gymkhana what is your recommended suolution?Hama
@Hama 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;Gymkhana

© 2022 - 2024 — McMap. All rights reserved.