the Printwriter.write() method just sends when I close the writer while the .println() method works fine
There seems there may be two problems here, the first having to do with writing and the second with reading:
The code creates a
PrintWriterwith automatic line flushing. When you useprintln, the new line results in the writer flushing. When usingwritewithout a new line, thePrintWriterdoes not flush (you can callout.flushafterout.writeto force a flush of theWriter).Presuming the receiving end is using
Scanner.readLine(), it expects a new line or will wait until it receives one.printlnautomatically appends the new line to the end of the String, withwriteyou must explicitly send the new lineout.write(line + "\n");
Yes I've absolutely seen this before. If you are using a PrintWriter or another Writer that has autoflush, you do not need to call flush(). But otherwise, to get the message to send, you've got to call flush() to get the content in the Writer / OutputStream to send.
The main difference is that System.out is a PrintStream and the other one is a PrintWriter. Essentially, PrintStream should be used to write a stream of bytes, while PrintWriter should be used to write a stream of characters (and thus it deals with character encodings and such).
For most use cases, there is no difference.
System.out is instance of PrintStream
So your question narrows down to PrintStream vs PrintWriter
All characters printed by a
PrintStreamare converted into bytes using the platform's default character encoding. (Syso writes out directly to system output/console)The
PrintWriterclass should be used in situations that require writing characters rather than bytes.