Java – How to get a new line character or \n?
The newline character, also called end of line (EOL), line break, line feed, line separator or carriage return, is a control character to tell the end of a line of text, and the next character should start at a new line. On the Windows system, it is \r\n
, on the Linux system, it is \n
.
In Java, we can use System.lineSeparator() to get a platform-dependent new line character.
package com.mkyong.io.howto;
public class GetNewLine {
public static void main(String[] args) {
System.out.print("Line 1");
// Windows \r\n, Linux \n
System.out.print(System.lineSeparator());
System.out.print("Line 2");
}
}
Output
Line 1
Line 2
P.S The System.getProperty("line.separator")
also returns the same result.
1. System.lineSeparator()
Here’s the System.lineSeparator()
method signature, available since Java 1.7, read the comments.
package java.lang;
public final class System {
/**
* Returns the system-dependent line separator string. It always
* returns the same value - the initial value of the {@linkplain
* #getProperty(String) system property} {@code line.separator}.
*
* <p>On UNIX systems, it returns {@code "\n"}; on Microsoft
* Windows systems it returns {@code "\r\n"}.
*
* @return the system-dependent line separator string
* @since 1.7
*/
public static String lineSeparator() {
return lineSeparator;
}
2. Print a newline character
If we want to print a platform-dependent new line character, try %n
(line separator) in String.format.
package com.mkyong.io.howto;
public class GetNewLine2 {
public static void main(String[] args) {
System.out.print(String.format("%s%n%s", "Line 1", "Line 2"));
}
}
Output
Line 1
Line 2
3. Write a newline character
If we use BufferedWriter
to write text to a file, the newLine()
represents the platform-dependent newline character.
package com.mkyong.io.howto;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public class GetNewLine3 {
public static void main(String[] args) {
// write a new line character
String fileName = "/home/mkyong/sample.txt";
List<String> content = Arrays.asList("A", "B", "C");
try (BufferedWriter bw = new BufferedWriter(new FileWriter(fileName))) {
for (String t : content) {
bw.write(t);
bw.newLine();
// same
//bw.write(System.lineSeparator());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Review the newLine()
method signature, internally, the BufferedWriter
also use System.lineSeparator()
.
package java.io;
public class BufferedWriter extends Writer {
/**
* Writes a line separator. The line separator string is defined by the
* system property {@code line.separator}, and is not necessarily a single
* newline ('\n') character.
*
* @exception IOException If an I/O error occurs
*/
public void newLine() throws IOException {
write(System.lineSeparator());
}
//...
}
Download Source Code
$ git clone https://github.com/mkyong/core-java
$ cd java-io
Thanks