Languages
[Edit]
EN

Java - how to get new line character for given platform eg Windows, Linux or MacOS - platform dependent?

14 points
Created by:
JustMike
26120

1. Overview:

In java it is possible to get platform dependent new line character in couple of ways:

  1. System.lineSeparator()
  2. System.getProperty("line.separator")
  3. String.format("%n")

2. New line character on most popular operating systems

Operating System Name New line character
Windows \r\n
Linux / Unix \n
MacOS \n

3. Java code example

public class Example {

    public static void main(String[] args) {

        String newLine1 = System.lineSeparator();
        String newLine2 = System.getProperty("line.separator");
        String newLine3 = String.format("%n");

        System.out.println(newLine1);
        System.out.println(newLine2);
        System.out.println(newLine3);
    }
}

When running on Windows:

Screenshot with 3 x ways in java how to get new line character - windows new character \r\n in intellij IDEA debugging session - https://dirask.com/q/8jme2j
Intellij IDEA debugging session - Windows new line \r\n

References

  1. Newline - wiki
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join