问题
How do I convert a byte array to a String in BlackBerry?
I have used
new String(bytearray,encoding type);
I am getting [B@fb5955d6
when calling toString().Can anyone help get this string in a readable format for BlackBerry?
回答1:
You don't show us where this byte data is coming from, or what value you expect it to have. So, I'm not sure I can fully debug your problem. But, hopefully this helps:
The reason you are seeing [B@fb5955d6
printed out when you simply call toString()
on your byte array is that the default implementation of toString() will just print out a short code for the array data type (e.g. byte
), and then something like an address (if you're familiar with C/C++) of your variable, which is almost never what you really want, especially in Java.
When you have binary data (as a byte[]
), Java doesn't know whether you intend that data to be a String
, or a ButtonField
, or a FuzzyWarble
. So, it has nothing more meaningful to print out than the object's address.
If you want to print out String
data, you need to create a String
object with the byte[]
, but to do that, you need to either use the default character encoding, or specify which encoding you want. "UTF-8"
and "ASCII"
are two popular encodings.
If I run this code
try {
byte[] bytes = new byte[] { 100, 67, 126, 35, 53, 42, 56, 126, 122 };
System.out.println("bytes are " + bytes.toString());
String s = new String(bytes, "UTF-8");
System.out.println("string is " + s);
} catch (UnsupportedEncodingException e1) {
}
I see this
bytes are [B@3b50e2ee
string is dC~#5*8~z
As you see, the address I see is different from the one you see (because I'm running on a different machine, with different memory layout). But, when converted to a String
with "UTF-8"
encoding, I see the value that you see.
So, maybe that's the right value?
Again, we don't know where the binary data comes from, or what it's supposed to be, but I can tell you that the code above is a typical way to convert byte arrays to strings.
回答2:
Try this -
byte[] byteArray = new byte[] {87, 79, 87, 46, 46, 46};
String value = new String(byteArray);
This will give you the value 'WOW..'
来源:https://stackoverflow.com/questions/14950019/convert-byte-array-to-string