Reputation: 31
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 "";
}
Upvotes: 2
Views: 2323
Reputation: 29814
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)
Upvotes: 1
Reputation: 1266
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.
Upvotes: 2