Java的outputStream在cmd上输出"\n"时不按预期工作。

huangapple go评论71阅读模式
英文:

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

问题

我正在尝试使用serverSocket,我发现当在cmd中连接并尝试使用"\n"来在下一行显示输出时,下一个字符串并不从行的开头开始:

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

CMD输出:

Java的outputStream在cmd上输出"\n"时不按预期工作。

英文:

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:

Java的outputStream在cmd上输出"\n"时不按预期工作。

答案1

得分: 3

信息

与其他操作系统不同,Windows使用"\r\n"作为换行符。
(还要注意命令行是带缓冲的。)

  • "\r" = CR = 回车 = 回到行首
  • "\n" = LF = 换行 = 转到下一行

这是经典的打字机控制"API"。

(回车是一种带有(通常是V形)用于打印字母的开口的小型轨道上的小车。首先向右移动小车,然后进一步按下卷起2个半行。)

我没有预料到在Windows/CMD.exe中仍然存在这种情况。

跨平台的方法是使用

System.lineSeparator().getBytes()
英文:

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()

huangapple
  • 本文由 发表于 2020年10月19日 15:48:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/64423144.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定