简体   繁体   中英

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.

The quote is copied from this web site.

I hard-coded an \\n , and the code below works on my Windows machine as expected.

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. So I downloaded JD GUI, opened the JAR file, and saw Hello\\nworld . Can anybody give me an example where \\n doesn't work and System.getProperty("line.separator") does?

There are different line separators, depends on the OS. Read this thread: What is the difference between \\r and \\n?

Excerpt of if:

More importantly, Unix tends to use \\n as a line separator; Windows tends to use \\r\\n as a line separator and Macs (up to OS 9) used to use \\r as the line separator. (Mac OS X is Unix-y, so uses \\n instead; there may be some compatibility situations where \\r is used instead though.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM