0

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.

6
  • possible duplicate of What is object serialization? Commented Aug 3, 2015 at 7:19
  • Have you added any thing in the Hashtable? Commented Aug 3, 2015 at 7:20
  • @Ankushsoni Yes, I just ignored it. Commented Aug 3, 2015 at 7:22
  • @dotvav Maybe but I don't want to save it into a file. Commented Aug 3, 2015 at 7:24
  • @James: which Jdk version are you using? Commented Aug 3, 2015 at 7:30

2 Answers 2

2

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();
Sign up to request clarification or add additional context in comments.

1 Comment

plus1 Since this may be the right way to go, consider to extend the answer a little more with an example. Thanks
1

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

1 Comment

My hash table has value, I just ignored it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.