\ n和\ r似乎无处不在.为什么line.separator更可移植? [英] \n and \r seem to work everywhere. Why is line.separator more portable?

查看:125
本文介绍了\ n和\ r似乎无处不在.为什么line.separator更可移植?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是仔细阅读问题,发现作者使用System.getProperty(line.separator)代替\n并认为代码是可移植的".通过各种论坛阅读,我看到了两个小组:

I was just perusing through questions, and I found System.getProperty(line.separator) used in place of \n with the author's comment that the code was "portable". Reading through various forums, I've seen two groups:

  1. 人们说Linux和Windows对换行符的解释有所不同,这弥补了这一点(没有明确的证据).
  2. 人们说通过显示代码和输出示例没有什么区别,这显然仅适用于该代码示例,而不是通用的.

我的感觉是:它可能是非标准的OS,例如您公司的工业扫描仪的OS,您会注意到其中的不同.什么时候可以看到\nline.separator之间的区别?你能举个例子吗?您如何发现变化发生的地方?

My feeling is: it's probably non-standard OS's, like for example your company's industrial scanner's OS for example, where you'll notice a difference. When am I going to see a difference between \n and line.separator? Can you show an example, please? How did you go about discovering where the variation occurs?

推荐答案

不正确的行尾经常引起麻烦.例如,这是Windows记事本在使用\n而不是\r\n(Windows的line.separator)写入文件时显示的内容:

Incorrect line endings are a frequent annoyance. For example, this is what Windows Notepad shows when writing a file with \n instead of \r\n (Windows' line.separator):

那些小盒子应该是换行符.

Those little boxes were supposed to be line breaks.

相反,当使用\r\n代替\n(Unix的line.separator)时,情况更糟,并且以怪异而奇妙的方式破坏了shell脚本和配置文件.

The other way around, when \r\n is used in place of \n (Unix' line.separator), is way worse, and breaks shell scripts and config files in weird and wonderful ways.

例如,这是sh在Debian和派生发行版上输出的内容,当尝试运行仅包含ls但带有\r\n行分隔符的shell脚本时(它看起来很浪费,因为回车会导致终端覆盖该行的一部分):

For example, this is what sh outputs on Debian and derived distros when trying to run a shell script that just contains ls but with \r\n line separators (it looks trashed because the carriage return causes the terminal to overwrite parts of the line):

: not foundsh: ls

每天都有一些关于StackOverflow的问题,这些问题被人们所咬,例如此处此处

There are several questions per day on StackOverflow from people being bitten by this, such as here, here and here.

这篇关于\ n和\ r似乎无处不在.为什么line.separator更可移植?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆