devxlogo

Cross-Platform Line Separators

Cross-Platform Line Separators

When your application generates multiple lines of output and is responsible for manually separating those lines, you may be inclined to insert an instance of the linefeed character (usually represented as ”
“). For example:

 java.io.Writer wr;...wr.write("First line");wr.write("
");wr.write("Second line");

While this code may work for many applications on some platforms, it is not portable code. That’s because different platforms traditionally use different line separators. For example, most Windows applications expect a carriage return/linefeed combination to mark the beginning of a new line. However, other platforms may only expect the carriage return character.

To ensure that your Java code will generate the appropriate character for the platform that it’s running on, use the System.getProperty() method to obtain the line separator dynamically as follows:

 java.io.Writer wr;...wr.write("First line");wr.write(System.getProperty("line.separator"));wr.write("Second line");

devx-admin

Share the Post: