将散列 table 转换为字节数组
Convert hash table to byte array
我有一个散列 table,我想通过数据报套接字发送它。
所以要做到这一点,我需要一个字节数组。
如何将哈希 table 转换为字节数组?
我忽略了填充哈希 table
我试过这样做:
Hashtable<String, String> valueNick = new Hashtable<>();
nickStr = valueNick.toString();
byte[] bufferNick = nickStr.getBytes();
for (int i = 0; i < bufferNick.length; i++) {
System.out.print(bufferNick[i] + " ");
}
但是什么也没有打印出来。
非常感谢您的帮助或建议。
为此目的考虑签出 ObjectOutputStream and ObjectInputStream
查看此 tutorial 示例和解释
下面是序列化table的例子:
ByteArrayOutputStream byteStream = new ByteArrayOutputStream(5000);
ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(byteStream));
// writes the object into a bytestream
oos.writeObject(valueNick);
oos.close();
byte[] sendBuf = byteStream.toByteArray();
// now send the sendBuf via a Datagram Socket
下面是读取对象的例子:
ByteArrayInputStream byteStream = new ByteArrayInputStream(recvBuf);
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(byteStream));
Hashtable<String, String> msg = (Hashtable<String, String>) ois.readObject();
ois.close();
我已经修改了代码(增加了它的价值)
Hashtable<String, String> valueNick = new Hashtable<>();
valueNick.put("name", "Ankush");
valueNick.put("lastName", "Soni");
String nickStr = valueNick.toString();
byte[] bufferNick = nickStr.getBytes();
for (int i = 0; i < bufferNick.length; i++) {
System.out.print(bufferNick[i] + " ");
} }
正在打印以下输出:
123 108 97 115 116 78 97 109 101 61 83 111 110 105 44 32 110 97 109
101 61 65 110 107 117 115 104 125
编辑: 使用空哈希表我也能够打印字节数据
123 125
我有一个散列 table,我想通过数据报套接字发送它。 所以要做到这一点,我需要一个字节数组。 如何将哈希 table 转换为字节数组? 我忽略了填充哈希 table 我试过这样做:
Hashtable<String, String> valueNick = new Hashtable<>();
nickStr = valueNick.toString();
byte[] bufferNick = nickStr.getBytes();
for (int i = 0; i < bufferNick.length; i++) {
System.out.print(bufferNick[i] + " ");
}
但是什么也没有打印出来。 非常感谢您的帮助或建议。
为此目的考虑签出 ObjectOutputStream and ObjectInputStream
查看此 tutorial 示例和解释
下面是序列化table的例子:
ByteArrayOutputStream byteStream = new ByteArrayOutputStream(5000);
ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(byteStream));
// writes the object into a bytestream
oos.writeObject(valueNick);
oos.close();
byte[] sendBuf = byteStream.toByteArray();
// now send the sendBuf via a Datagram Socket
下面是读取对象的例子:
ByteArrayInputStream byteStream = new ByteArrayInputStream(recvBuf);
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(byteStream));
Hashtable<String, String> msg = (Hashtable<String, String>) ois.readObject();
ois.close();
我已经修改了代码(增加了它的价值)
Hashtable<String, String> valueNick = new Hashtable<>();
valueNick.put("name", "Ankush");
valueNick.put("lastName", "Soni");
String nickStr = valueNick.toString();
byte[] bufferNick = nickStr.getBytes();
for (int i = 0; i < bufferNick.length; i++) {
System.out.print(bufferNick[i] + " ");
} }
正在打印以下输出:
123 108 97 115 116 78 97 109 101 61 83 111 110 105 44 32 110 97 109 101 61 65 110 107 117 115 104 125
编辑: 使用空哈希表我也能够打印字节数据
123 125