问题
So I want to convert a byte array returned by the DatagramPacket's getData() function into a string. I know the way to convert the whole byte array to string is just:
String str = new String(bytes);
However, this prints out null characters at the end. So if the byte array was
[114, 101, 113, 117, 101, 115, 116, 0, 0, 0]
The 0's print out empty boxes on the console. So I basically only want to print out:
[114, 101, 113, 117, 101, 115, 116]
So I made this function:
public void print(DatagramPacket d) {
byte[] data = d.getData();
for(int i=0; i< d.getLength(); i++) {
if(data[i] != 0)
System.out.println( data[i] );
}
}
But unfortunately this is printing out the actual numbers instead of the letters. So how can I convert each individual byte to a string and print that out. Or if there is another way to print the byte array without the nulls at the end then that'll be fine too.
回答1:
Just cast each int, that is not 0, to a char. You can test it in your print:
System.out.println((char)data[i]);
回答2:
If you want to convert byte array into String then you can just use
String(byte[] bytes)
or String(byte[] bytes, Charset charset)
constructors like,
byte[] b=new byte[10];
b[0]=100;
b[1]=101;
b[2]=102;
b[3]=0;
b[4]=0;
String st=new String(b);
System.out.println(st);//def
but if you want to print single character then
char[] c=st.toCharArray();
for(int i=0;i<c.length;i++){
System.out.println(c[i]);
}
来源:https://stackoverflow.com/questions/20112935/java-byte-to-string