Search This Blog

Showing posts with label newline. Show all posts
Showing posts with label newline. Show all posts

Why FileOutputStream or BufferedWriter Does Not Write New Line to File

The new-line character is system dependent. It depends on operating system. It can be \n, \r, \r\n or something else depending on the operating system. So, when we are writing a cross platform java program, it is important to take care when we use a line separator or new line character. It is always safe to use system specific line separator provided by JVM. You can get the system specific newline character in different ways.

Method 1:

System.lineSeparator() instead of new line character. The java method Sytem.lineSeparator() returns the newline character (line separator) as a strong. If you are appending a string on another with a line separator in between, it can be done as follows.

line1+System.lineSeparator()+line2

Method 2:

You can also get the line separator using the getProperty() method with property key line.separator.

System.getProperty("line.separator");

Method 3:

If your are using a BufferedReader object to write text into a file, you can use the newLine() method to write a newline into the file. If br is a BufferedReader object, br.newLine() will write a newline (line separator) into the file.

Method 4:

If you want to get the line separator as a character, you may use the static member Character.LINE_SEPARATOR. It returns the Unicode newline character.