英文:
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输出:
英文:
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:
答案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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论