Search code examples
javacmdprintingserversocketoutputstream

Java outputStream "\n" not working as expected on cmd


I am playing around with serverSocket, i found that when connecting in cmd and trying to display output on next line using "\n" the next string does not start from the beginning of the line:

for (int i = 0; i <10; i++) {
    outputStream.write(("Time is " + new Date() + "\n").getBytes());
    Thread.sleep(1000);
}

CMD output:

cmd


Solution

  • Info

    Unlike other operating systems with "\n" as line break, Windows has "\r\n". (Also mind that the command line is buffered.)

    • "\r" = CR = Carriage Return = go to the beginning of the line
    • "\n" = LF = Line Feed = go to next line

    This is the classical type writer control "API."

    (Carriage is a small carriage on a rail with a (ofter V-form) opening for printing a letter. A handle to the right first moves the carriage to the left, and further pressing moves the roll up 2 half-lines.)

    I would not have expected to see this demonstrated as still to exist in Windows/CMD.exe.

    Platform independant would be to use

    System.lineSeparator().getBytes()