Platform-dependent newline character in Java
In many situations, you may need to use platform-dependent newline character in Java. There are several ways you can get that value, depending on the Java version you are using.
Java system properties always includes
line.separator property which contains platform-dependent line separator (
\n on UNIX and
\r\n on Microsoft Windows). You can get that value using System.getProperty() method e.g.
final String newline = System.getProperty("line.separator");
Note that this method can be used with any Java version.
If you are using Java 1.7 or later, you can use dedicated method returning platform-dependent newline value: System.lineSeparator():
final String newline = System.lineSeparator();
Full set of always included properties can be found at System.getProperties() Javadoc page.
In addition to the system property of a dedicated method, you can use
String.format (or other formatting methods) and
%n token. As you can find on Format String Syntax,
%n token is substituted with the platform-specific line separator in the output string e.g.
final String value = String.format("example%n"); // value = "example\n"
final String value = String.format("example%n"); // value = "example\r\n"
Note that this works if you are using Java 1.5 or later.
You may also be interested in:
- The first 500 Fibonacci numbers
- High-performance Fibonacci numbers implementation in Go
- GIF image creation in Go tutorial
comments powered by Disqus