2

I want to send several strings from A to B using the DataInputStream.

I know how to send these across using .write() but I'm unsure of the best method to seperate the strings. In fact - after research, it doesn't seem as if it's possible unless I add a character in the string and split at B.

Any alternatives to using the DataInputStream would be considered. I was going to create a Array and send that across, although I wasn't sure how to do it.

So far I have:

public String getDetails() {       
 System.out.print("Name: ");
 String uiname = scan.next();
 pout.write(uiname);

 System.out.print("Address: ");
 String uiaddress = scan.next();

 pout.write(uiaddress);

 return "";

}

David Jackson
  • 31
  • 2
  • 6
  • what's your problem with using `DataInput-/OutputStream`? If you're using it, you're sending binary data. No need to separate your strings as they're sent as single objects. – Zhedar Mar 22 '13 at 14:39
  • I have the streams working, but when I print the stream out at B, it joins all of the strings together. I was just wondering of a way around this. There must be a better method compared to how I have attempted it. – David Jackson Mar 22 '13 at 14:40

2 Answers2

2

As long as your strings are < 65536 characters long, you can use DataOutputStream.writeUtf() and DataInputStream.readUTF(). If you needs something more complex than strings and primitives, you'll need to use ObjectOutputStream and ObjectInputStream.

Example (which may contain syntax errors):

DataOutputStream out = new DataOutputStream(...);
out.writeUtf("foo");
out.writeUtf("bar");
out.close();

DataInputStream in = new DataInputStream(...);
String s1 = in.readUtf();
String s2 = in.readUtf();
// that's all, folks!

The writeUtf() method preceeds the string with a count of its characters. The readUtf() method first gets the character count, then reads exactly that many characters. As long as you're just writing/reading strings, the streams can figure it out.

parsifal
  • 1,246
  • 6
  • 8
1

Two ideas:

  • Use DataOutputStream.writeUTF and DataInputStream.readUTF

  • Use a "holder" format like JSON (or XML) and build a JSON Array that you "print" then decode at the other end using any of the numerous libraires to do that (the JSON library at json.org is sufficient for the task)

Bruno Grieder
  • 28,128
  • 8
  • 69
  • 101