Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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

like image 719
Guy Rich Avatar asked Apr 28 '11 18:04

Guy Rich


People also ask

Can we convert byte array to String in Java?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.

Can you print [] byte?

You can simply iterate the byte array and print the byte using System. out. println() method.


Video Answer


2 Answers

String s = new String(myByteArray, "UTF-8");
StringBuilder sb = new StringBuilder(s);
like image 188
helpermethod Avatar answered Oct 07 '22 13:10

helpermethod


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.

like image 5
Itay Maman Avatar answered Oct 07 '22 11:10

Itay Maman