开发者

How can I convert bytearray to String

开发者 https://www.devze.com 2023-02-21 17:44 出处:网络
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.

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;    
whi开发者_如何学Pythonle(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);


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.


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


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

精彩评论

暂无评论...
验证码 换一张
取 消