How might I, in Java, convert a StringBuffer to a byte array?
Convert a StringBuffer to a byte Array in Java
Asked Answered
I say we have an answer, from Greg:
String.valueOf(stringBuffer).getBytes()
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 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();
}
I say we have an answer, from Greg:
String.valueOf(stringBuffer).getBytes()
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.
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