Search code examples
blackberryblackberry-simulatorblackberry-eclipse-plugin

How can I convert bytearray to String


I am extracting metadata of a song using following code ,And how I can convert the byte array (buf) to string? Please help me,Thanks in advance.

String mint = httpConnection.getHeaderField("icy-metaint");
int b = 0;
int count =0;    
while(count++ < length){
b = inputStream.read();         
}            
int metalength = ((int)b)*16;
if(metalength <= 0)
    return;
byte buf[] = new byte[metalength];
inputStream.read(buf,0,buf.length);

Solution

  • 1). Read bytes from the stream:

    // use net.rim.device.api.io.IOUtilities
    byte[] data = IOUtilities.streamToBytes(inputStream);
    

    2). Create a String from the bytes:

    String s = new String(data, "UTF-8");
    

    This implies you know the encoding the text data was encoded with before sending from the server. In the example right above the encoding is UTF-8. BlackBerry supports the following character encodings:

    * "ISO-8859-1"
    * "UTF-8"
    * "UTF-16BE"
    * "US-ASCII" 
    

    The default encoding is "ISO-8859-1". So when you use String(byte[] data) constructor it is the same as String(byte[] data, "ISO-8859-1").

    If you don't know what encoding the server uses then I'd recommend to try UTF-8 first, because by now it has almost become a default one for servers. Also note the server may send the encoding via an http header, so you can extract it from the response. However I saw a lot of servers which put "UTF-8" into the header while actually use ISO-8859-1 or even ASCII for the data encoding.