问题
The following code prints
[B@40545a60,[B@40545a60abc exp
But I want to print abc
, so that I can retrieve the correct message from the receiving system.
public class Operation {
InetAddress ip;
DatagramSocket dsock;
DatagramPacket pack1;
byte[] bin,bout;
WifyOperation(InetAddress Systemip)
{
ip=Systemip;
try {
dsock=new DatagramSocket();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
void sendbyte()
{
String senddata="abc";
bout=senddata.getBytes();
pack1=new DatagramPacket(bout,bout.length,ip,3322);
try {
dsock.send(pack1);
Log.d(pack1.getData().toString(),"abc exp");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
How can I retrieve string instead of byte from the packet pack1
?
回答1:
New answer based on comment:
Indeed, my old answer was incorrect. Update:
String str = new String(
pack1.getData(),
pack1.getOffset(),
pack1.getLength(),
StandardCharsets.UTF_8 // or some other charset
);
Old answer:
Do something like:
byte[] data = pack1.getData();
InputStreamReader input = new InputStreamReader(
new ByteArrayInputStream(data), Charset.forName("UTF-8"));
StringBuilder str = new StringBuilder();
for (int value; (value = input.read()) != -1; )
str.append((char) value);
This assumes the byte data represents (just) UTF-8 text, which may not be the case.
回答2:
You can try:
String msg = new String(pack1.getData(), pack1.getOffset(), pack1.getLength());
来源:https://stackoverflow.com/questions/10159732/how-to-retrieve-string-from-datagrampacket