How might I, in Java, convert a StringBuffer to a byte array?
            Asked
            
        
        
            Active
            
        
            Viewed 5.6k times
        
    34
            
            
        - 
                    9can you just do String.valueOf(stringBuffer).getBytes()? – Greg Giacovelli Nov 04 '11 at 05:50
- 
                    9Make 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. – Nov 04 '11 at 06:03
2 Answers
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();
}
 
    
    
        Harshal Waghmare
        
- 1,944
- 2
- 20
- 21
35
            I say we have an answer, from Greg:
String.valueOf(stringBuffer).getBytes()
 
    
    
        Jeff Grigg
        
- 1,004
- 8
- 7
- 
                    2this 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 Sep 30 '22 at 05:39
- 
                    
- 
                    @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;` – chendu Feb 06 '23 at 04:34
 
    