简体   繁体   English

将包含字节数组值的字符串转换为字节数组

[英]convert a string holding byte array values to byte array

I'm reading messages from a TCP connection. 我正在从TCP连接中读取消息。 The sender is sending a byte array but the BufferedReader reads it as a string. 发送方正在发送字节数组,但是BufferedReader会将其读取为字符串。 How can I convert the message to a byte array so I can then convert it to the actual message? 如何将消息转换为字节数组,以便随后将其转换为实际消息?

Say I want to send "hello". 说我要发送“你好”。 I use 我用

String message = "hello"
byte[] byteData = message.getBytes();

I then send the message. 然后,我发送消息。 It's received as a string of, say, 0Bf3f3 . 它以字符串形式接收,例如0Bf3f3 I need to convert it back to "hello". 我需要将其转换回“ hello”。

java.lang.String provides a constructor which takes an array of bytes. java.lang.String提供了一个构造方法,该构造方法使用字节数组。 However, you need to keep in mind that the charset can be different at the receiver and sender side. 但是,您需要记住,接收方和发送方的字符集可以不同。 For more details, see the javadoc . 有关更多详细信息,请参见javadoc

This is how to convert a byte array back to a String: 这是将字节数组转换回字符串的方法:

String message = "hello";
byte[] byteData = message.getBytes();
String retMessage = new String(byteData); // <===

将缓冲的输入流用于字节数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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