James Parson
James Parson

Reputation: 63

Convert hash table to byte array

I have a hash table and I want to send it through by Datagram Socket. So to do this I need to have a byte array. How can I convert my hash table to a byte array? I've ignore filling a hash table I've tried do this by this way:

    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] + " ");
        }

But nothing has been printed. Thanks very much for any help or advise.

Upvotes: 0

Views: 3342

Answers (2)

Harsh Poddar
Harsh Poddar

Reputation: 2554

Consider checking out ObjectOutputStream and ObjectInputStream for this purpose

Check out this tutorial for an example and explanation

The following is an example to serialize the 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

The following is an example to read the object:

ByteArrayInputStream byteStream = new ByteArrayInputStream(recvBuf);
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(byteStream));
Hashtable<String, String> msg = (Hashtable<String, String>) ois.readObject();
ois.close();

Upvotes: 2

Ankush soni
Ankush soni

Reputation: 1459

I have modified the code(added value in it)

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] + " ");
            }   }

It is printing below output:

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

Edit: With the empty Hashtable also I am able to print the byte data which is

123 125

Upvotes: 1

Related Questions