I've been struggling with this for a while now. I'm working on a client/server architecture where I send multi-lined messages across the network. One example of this is a final report that is sent from a Client to the Server, I'm trying to get each line of the message and store it in a String array so that I may manipulate it later. My code only prints the first line of the report and nothing else, however, does that mean the message isn't getting stored in my array properly? Or should I be doing something else to show the result?
My Code.
DataInputStream network = new DataInputStream(sock.getInputStream());
String FullReport[] = new String[15];
for(int i = 0; i < FullReport.length; ++i)
{
String message = network.readUTF();
FullReport[i] = message;
//Store NHS Number, Date, Time, Location, Cause, Description, Action
//Send this information to KwikMedical to be stored in the database
}
System.out.println("\n" + FullReport.toString());
Any ideas why my code doesn't give me the desired output?
Thanks!
Joe Clark
Full-stack developer specializing in healthcare IT
In your System.out.println, you probably want String.join("\n", FullReport) instead.
That said, unless you know for sure your DataInputStream is exactly 15 lines long every time, I'd recommend something different, and that is using an ArrayList, and reading until there's no more data. The ArrayList will let you dynamically size a little easier than pre-defining your array size. But, again, this is useful when the amount of data being received is unknown.
ArrayList<String> FullReport = new ArrayList<String>(); while (network.available() > 0) { FullReport.add(network.readUTF()); } for (String Report : FullReport) { System.out.println(Report); }It's of note that System.out.println automatically adds the "\n", so you probably don't need to do that yourself.
Disclaimer: This is untested. There's probably bugs.