简体   繁体   中英

How best to convert a byte[] array to a string buffer

I have a number of byte[] array variables I need to convert to string buffers.

is there a method for this type of conversion?

Thanks

Thank you all for your responses..However I didn't make myself clear.... I'm using some byte[] arrays pre-defined as public static "under" the class declaration for my java program. these "fields" are reused during the "life" of the process. As the program issues status messages, (written to a file) I've defined a string buffer (mesg_data) that used to format a status message. So as the program executes I tried msg2 = String(byte_array2) I get a compiler error: cannot find symbol symbol: method String(byte[]) location: class APPC_LU62.java.LU62XnsCvr convrsID = String(conversation_ID);

example:

public class LU62XnsCvr extends Object
           .
           .
static String convrsID ; 
static byte[] conversation_ID = new byte[8] ;

So I can't use a "dynamic" define of a string variable because the same variable is used in multiple occurances.

I hope I made myself clear Thanks ever so much

Guy

String s = new String(myByteArray, "UTF-8");
StringBuilder sb = new StringBuilder(s);

There is a constructor that a byte array and encoding:

 byte[] bytes = new byte[200];
 //...

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

In order to translate bytes to characters you need to specify encoding: the scheme by which sequences (typically of length 1,2 or 3) of 0-255 values (that is: sequence of bytes) are mapped to characters. UTF-8 is probably the best bet as a default.

You can turn it to a String directly

byte[] bytearray
....
String mystring = new String(bytearray)

and then to convert to a StringBuffer

StringBuffer buffer = new StringBuffer(mystring)

You may use

str = new String(bytes)

By thewhat the code above does is to create a java String (ie UTF-16) with the default platform character encoding.

If the byte array was created from a string encoded in the platform default character encoding this will work well.

If not you need to specify the correct character encoding (Charset) as

String str = new String (byte [] bytes, Charset charset)

It depends entirely on the character encoding, but you want:

String value = new String(bytes, "US-ASCII");

This would work for US-ASCII values.

SeeCharset for other valid character encodings (eg, UTF-8)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM