How do I convert a byte array to a string? Is this the correct syntax?
byteArray.toString();
Adrian Toman
11.5k6 gold badges50 silver badges63 bronze badges
asked Nov 25, 2010 at 9:26
-
Have you tried it? Was there a problem?Marcelo Cantos– Marcelo Cantos2010年11月25日 09:29:47 +00:00Commented Nov 25, 2010 at 9:29
-
1what does the compiler say? "Computer Says No!"???Mitch Wheat– Mitch Wheat2010年11月25日 09:29:57 +00:00Commented Nov 25, 2010 at 9:29
-
@ Mitch Wheat i am getting different anwsers for bytearray.toString() and public void convertByteArrayToString() { byte[] byteArray = new byte[] {87, 79, 87, 46, 46, 46}; String value = new String(byteArray); System.out.println(value); }xydev– xydev2010年11月25日 10:32:27 +00:00Commented Nov 25, 2010 at 10:32
2 Answers 2
The Best way to convert bytearray to String is
public void convertByteArrayToString(Charset encoding) {
byte[] byteArray = new byte[] {87, 79, 87, 46, 46, 46};
String value = new String(byteArray, encoding);
System.out.println(value);
}
Christoffer Hammarström
28k4 gold badges52 silver badges59 bronze badges
answered Nov 25, 2010 at 9:32
Sign up to request clarification or add additional context in comments.
4 Comments
Nick H
String(byte[]) uses the system's default encoding. You should use String(byte[], String) to specify an encoding, which depends on what your encoding your bytes are in.
xydev
@Nick i am getting an error String value = new String(byteArray, "text/xml; charset=utf-8"); as unsupported encoding exception
xydev
@Nick also tried String value = new String(byteArray, "charset=utf-8");
Nick H
It should be a string such as
UTF-8
. See download.oracle.com/javase/1.4.2/docs/api/java/nio/charset/… for some standard charsets.You need to supply an encoding, otherwise you get the system default encoding, essentially a random value.
String value = new String(byteArray, encoding);
answered Dec 11, 2012 at 12:24
Comments
lang-java