在Java中将字符转换为字节,将字符串转换为字节

在Java中将字符转换为字节,将字符串转换为字节,java,Java,我一直在使用套接字发送数据,发送的数据是一个带有消息结构的ASCII协议。消息的结构在此链接中。这是我到目前为止制定的代码 Socket socket = new Socket(host, port); DataOutputStream out = new DataOutputStream(socket.getOutputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputS

我一直在使用套接字发送数据,发送的数据是一个带有消息结构的ASCII协议。消息的结构在此链接中。这是我到目前为止制定的代码

Socket socket = new Socket(host, port);
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.write(byte_array); //Send data to the socket
out.flush();

String reply = in.readLine(); //Read for any response returned by the server
System.out.println("Reply from Server: " + reply);
我的问题是,是否有一种替代方法来代替在发送之前将字符转换为字节,在发送之前将字符串转换为字节。这是将转换发送到套接字之前的当前代码

byte[] byte_array = new byte[] {7, charToByte('0'), charToByte('5'), charToByte('N'), charToByte('R'), charToByte('X'), 13};
public static byte charToByte(char a)
{
    return (byte)(a & 0xFF);
}

因此,基本上我想知道是否有方法将字符串“\a01NIP\r”转换为字节,因为我尝试了
getBytes()
,但得到的结果是“来自服务器的回复:null”。

System.out.println(Arrays.toString((Character.toString((char)7)+“01NIP\r”).getBytes(“UTF-8”)您是否尝试过
新字节[]{7,0,5,N,R,X,13}
?另外,您的默认编码是什么?[link]在消息结构链接上更新