[英]If we're told to use the system property line.separator instead of hard-coding \n, why does my code work on Windows?
We all read something like this: 我们都读过这样的东西:
use the System.getProperty(String) method to refer to items which depend on the system, such as line terminators and path separators. 使用System.getProperty(String)方法来引用依赖于系统的项目,例如行终止符和路径分隔符。
The quote is copied from this web site. 报价是从该网站复制的。
I hard-coded an \\n
, and the code below works on my Windows machine as expected. 我对\\n
硬编码,并且下面的代码可以在Windows计算机上正常运行。
package sample;
public class Main {
public static void main(String[] args) {
System.out.println("hello\nworld");
};
}
The output is: 输出为:
hello
world
I thought the Java compiler replaced \\n
with \\r\\n
silently. 我以为Java编译器会以无声方式将\\n
替换为\\r\\n
。 So I downloaded JD GUI, opened the JAR file, and saw Hello\\nworld
. 因此,我下载了JD GUI,打开了JAR文件,并看到Hello\\nworld
。 Can anybody give me an example where \\n
doesn't work and System.getProperty("line.separator")
does? 谁能给我一个例子,其中\\n
不起作用,而System.getProperty("line.separator")
起作用吗?
There are different line separators, depends on the OS. 有不同的行分隔符,取决于操作系统。 Read this thread: What is the difference between \\r and \\n? 阅读此线程: \\ r和\\ n有什么区别?
Excerpt of if: 如果摘录:
More importantly, Unix tends to use \\n as a line separator; 更重要的是,Unix倾向于使用\\ n作为行分隔符; Windows tends to use \\r\\n as a line separator and Macs (up to OS 9) used to use \\r as the line separator. Windows倾向于将\\ r \\ n用作行分隔符,而Mac(直到OS 9)则倾向于将\\ r用作行分隔符。 (Mac OS X is Unix-y, so uses \\n instead; there may be some compatibility situations where \\r is used instead though.) (Mac OS X是Unix-y,因此改用\\ n;但是在某些兼容性情况下,改用\\ r。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.