Question

I was wondering if it's possible to send a single string with newline characters using BufferedWriter.

For context I need to send the following string over the network:

String message = "LOOKREPLY\nX...X\n.....\n.....\n.....\nX...X"
socketOutput = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
socketOutput.write(message + "\n");

But this sends 6 messages over the network because of the newline characters. I could re-build it on the client side but was wondering if there's a neater/simpler approach.

Was it helpful?

Solution

In your code

bw.write(message+"\n");

As it will put \n after all message has been written.

BufferedWriter will not send 6 Messages it will send only one but as you gave \n in your string it will write according to that.

As delv said you can put escape sequence to the \n so that it will write only one line.

String message = "LOOKREPLY\\nX...X\\n.....\\n.....\\n.....\\nX...X";

So that message will be written like this.

LOOKREPLY\nX...X\n.....\n.....\n.....\nX...X
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top