Jisson
Jisson

Reputation: 3725

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

Upvotes: 1

Views: 1968

Answers (3)

Vit Khudenko
Vit Khudenko

Reputation: 28418

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.

Upvotes: 3

gop
gop

Reputation: 2200

As @Heiko mentioned you can create string directly using the constructor. This applies to blackberry java too:

byte[] array = {1,2,3,4,5}; 
String str = new String(array);

Upvotes: 1

Heiko Rupp
Heiko Rupp

Reputation: 30934

String has a constructor that accepts a byte array that you can use for this. See e.g. http://java.sun.com/javame/reference/apis/jsr139/java/lang/String.html

Upvotes: 2

Related Questions