How to get the default new line character in Java ?

In Windows, the default new line character is ‘n’ . However, depending on the OS, say Unix ( also ‘n’ fortunately ), Mac, linux, the new line character might change. If you are writing an app that is supposed to work across platforms, you cannot take a chance with this. So, how do you get the OS/Platform specific new line character ?

Fortunately, Java captures this using one of its  System Properties

[java title=”HelloWorld.java” gutter=”true” highlight=”1″]
System.getProperty("line.separator");
[/java]

Easy, right ? So, let’s say you are reading the lines in a file and want to preserve the new lines. Here is how you can use it.

[java title=”HelloWorld.java” gutter=”true” highlight=”9″]
try
{
FileReader fr = new FileReader("read_text.txt");
BufferedReader br = new BufferedReader ( fr);

//read each line of the file
while ( ( temp = br.readLine()) != null)
{
file_text.append(temp);
file_text.append(System.getProperty("line.separator"));
}
} catch (IOException e)
{
System.out.println (" Error during file read -> " + e);
}
[/java]

This way, you can be sure that you are getting the right OS specific line delimiter. Ask your Java Training instructor to explain more about System Properties.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s