snippetjavaCritical
How do I get a platform-independent new line character?
Viewed 0 times
independenthowlinecharacterplatformnewget
Problem
How do I get a platform-independent newline in Java? I can’t use
"\n" everywhere.Solution
In addition to the line.separator property, if you are using java 1.5 or later and the String.format (or other formatting methods) you can use
See the Java 1.8 API for Formatter for more details.
%n as inCalendar c = ...;
String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY%n", c);
//Note `%n` at end of line ^^
String s2 = String.format("Use %%n as a platform independent newline.%n");
// %% becomes % ^^
// and `%n` becomes newline ^^See the Java 1.8 API for Formatter for more details.
Code Snippets
Calendar c = ...;
String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY%n", c);
//Note `%n` at end of line ^^
String s2 = String.format("Use %%n as a platform independent newline.%n");
// %% becomes % ^^
// and `%n` becomes newline ^^Context
Stack Overflow Q#207947, score: 377
Revisions (0)
No revisions yet.