Platform Independent New Line Character in Java

Unix, Windows/DOS, and Mac have somewhat different newline characters to indicate the end-of-line. Unix uses ‘\n’ (linefeed) as the line separator. Some Windows/DOS application programs allow ‘\n’ as the newline character, but many expect a pair of characters ‘\r\n’ (carriage return followed by line feed). For example, Windows application notepad expects ‘\r\n’ for a newline. Some Mac applications require ‘\r\n’ for newline whereas the majority of the Mac applications work like Unix system and need only ‘\n\ for the newline.

To overcome this issue, Java came up with its own platform independent newline character definition. You can declare newline string in your program as follows…

String newline = System.getProperty(“line.separator”);

You can look into the following program as a reference.

import java.io.*;

class TextWriter{
    String newline = System.getProperty("line.separator");
    
    TextWriter(){
        try{
            File file = new File("temp.txt");
            FileOutputStream fileStream = new FileOutputStream(file);
            write(fileStream, "username=Hello");
            write(fileStream, "level=5");
        }catch(IOException e){
            System.out.println("Couldn't write file");
        }
    }
    
    void write(FileOutputStream stream, String output) throws IOException{
        output = output + newline;
        byte[] data = output.getBytes();
        stream.write(data, 0, data.length);
    }
    
    public static void main(String[] args){
        TextWriter tw = new TextWriter();
    }
}

The output file has both the strings on different lines. The output was generated on Ubuntu machine.

username=Hello
level=5

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.